focal_method
stringlengths 13
60.9k
| test_case
stringlengths 25
109k
|
---|---|
public static Map<String, ShardingSphereSchema> build(final GenericSchemaBuilderMaterial material) throws SQLException {
return build(getAllTableNames(material.getRules()), material);
}
|
@Test
void assertLoadWithExistedTableName() throws SQLException {
Collection<String> tableNames = Collections.singletonList("data_node_routed_table1");
when(MetaDataLoader.load(any())).thenReturn(createSchemaMetaDataMap(tableNames, material));
assertFalse(GenericSchemaBuilder.build(tableNames, material).get(DefaultDatabase.LOGIC_NAME).getTables().isEmpty());
}
|
public void setLastColdReadTimeMills(Long lastColdReadTimeMills) {
this.lastColdReadTimeMills = lastColdReadTimeMills;
}
|
@Test
public void testSetLastColdReadTimeMills() {
long newLastColdReadTimeMills = System.currentTimeMillis() + 1000;
accAndTimeStamp.setLastColdReadTimeMills(newLastColdReadTimeMills);
assertEquals("Last cold read time should be set to new value", newLastColdReadTimeMills, accAndTimeStamp.getLastColdReadTimeMills().longValue());
}
|
public void clear() {
for (Section s : sections) {
s.clear();
}
}
|
@Test
public void testClear() {
ConcurrentLongPairSet map = ConcurrentLongPairSet.newBuilder()
.expectedItems(2)
.concurrencyLevel(1)
.autoShrink(true)
.mapIdleFactor(0.25f)
.build();
assertTrue(map.capacity() == 4);
assertTrue(map.add(1, 1));
assertTrue(map.add(2, 2));
assertTrue(map.add(3, 3));
assertTrue(map.capacity() == 8);
map.clear();
assertTrue(map.capacity() == 4);
}
|
@Override
protected void doProcess(Exchange exchange, MetricsEndpoint endpoint, MetricRegistry registry, String metricsName)
throws Exception {
Message in = exchange.getIn();
Counter counter = registry.counter(metricsName);
Long increment = endpoint.getIncrement();
Long decrement = endpoint.getDecrement();
Long finalIncrement = getLongHeader(in, HEADER_COUNTER_INCREMENT, increment);
Long finalDecrement = getLongHeader(in, HEADER_COUNTER_DECREMENT, decrement);
if (finalIncrement != null) {
counter.inc(finalIncrement);
} else if (finalDecrement != null) {
counter.dec(finalDecrement);
} else {
counter.inc();
}
}
|
@Test
public void testProcessWithDecrementOnly() throws Exception {
Object action = null;
when(endpoint.getIncrement()).thenReturn(null);
when(endpoint.getDecrement()).thenReturn(DECREMENT);
when(in.getHeader(HEADER_COUNTER_DECREMENT, DECREMENT, Long.class)).thenReturn(DECREMENT);
producer.doProcess(exchange, endpoint, registry, METRICS_NAME);
inOrder.verify(exchange, times(1)).getIn();
inOrder.verify(registry, times(1)).counter(METRICS_NAME);
inOrder.verify(endpoint, times(1)).getIncrement();
inOrder.verify(endpoint, times(1)).getDecrement();
inOrder.verify(in, times(1)).getHeader(HEADER_COUNTER_INCREMENT, action, Long.class);
inOrder.verify(in, times(1)).getHeader(HEADER_COUNTER_DECREMENT, DECREMENT, Long.class);
inOrder.verify(counter, times(1)).dec(DECREMENT);
inOrder.verifyNoMoreInteractions();
}
|
@Override
public long transferFrom(ReadableByteChannel src, long position, long count) throws IOException {
checkNotNull(src);
Util.checkNotNegative(position, "position");
Util.checkNotNegative(count, "count");
checkOpen();
checkWritable();
long transferred = 0; // will definitely either be assigned or an exception will be thrown
if (append) {
// synchronize because appending does update the channel's position
synchronized (this) {
boolean completed = false;
try {
if (!beginBlocking()) {
return 0; // AsynchronousCloseException will be thrown
}
file.writeLock().lockInterruptibly();
try {
position = file.sizeWithoutLocking();
transferred = file.transferFrom(src, position, count);
this.position = position + transferred;
file.setLastModifiedTime(fileSystemState.now());
completed = true;
} finally {
file.writeLock().unlock();
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} finally {
endBlocking(completed);
}
}
} else {
// don't synchronize because the channel's position is not involved
boolean completed = false;
try {
if (!beginBlocking()) {
return 0; // AsynchronousCloseException will be thrown
}
file.writeLock().lockInterruptibly();
try {
transferred = file.transferFrom(src, position, count);
file.setLastModifiedTime(fileSystemState.now());
completed = true;
} finally {
file.writeLock().unlock();
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} finally {
endBlocking(completed);
}
}
return transferred;
}
|
@Test
public void testTransferFromNegative() throws IOException {
FileChannel channel = channel(regularFile(0), READ, WRITE);
try {
channel.transferFrom(new ByteBufferChannel(10), -1, 0);
fail();
} catch (IllegalArgumentException expected) {
}
try {
channel.transferFrom(new ByteBufferChannel(10), 0, -1);
fail();
} catch (IllegalArgumentException expected) {
}
}
|
public static List<AclEntry> replaceAclEntries(List<AclEntry> existingAcl,
List<AclEntry> inAclSpec) throws AclException {
ValidatedAclSpec aclSpec = new ValidatedAclSpec(inAclSpec);
ArrayList<AclEntry> aclBuilder = Lists.newArrayListWithCapacity(MAX_ENTRIES);
// Replacement is done separately for each scope: access and default.
EnumMap<AclEntryScope, AclEntry> providedMask =
Maps.newEnumMap(AclEntryScope.class);
EnumSet<AclEntryScope> maskDirty = EnumSet.noneOf(AclEntryScope.class);
EnumSet<AclEntryScope> scopeDirty = EnumSet.noneOf(AclEntryScope.class);
for (AclEntry aclSpecEntry: aclSpec) {
scopeDirty.add(aclSpecEntry.getScope());
if (aclSpecEntry.getType() == MASK) {
providedMask.put(aclSpecEntry.getScope(), aclSpecEntry);
maskDirty.add(aclSpecEntry.getScope());
} else {
aclBuilder.add(aclSpecEntry);
}
}
// Copy existing entries if the scope was not replaced.
for (AclEntry existingEntry: existingAcl) {
if (!scopeDirty.contains(existingEntry.getScope())) {
if (existingEntry.getType() == MASK) {
providedMask.put(existingEntry.getScope(), existingEntry);
} else {
aclBuilder.add(existingEntry);
}
}
}
copyDefaultsIfNeeded(aclBuilder);
calculateMasks(aclBuilder, providedMask, maskDirty, scopeDirty);
return buildAndValidateAcl(aclBuilder);
}
|
@Test(expected=AclException.class)
public void testReplaceAclDefaultEntriesInputTooLarge() throws AclException {
List<AclEntry> existing = new ImmutableList.Builder<AclEntry>()
.add(aclEntry(DEFAULT, USER, ALL))
.add(aclEntry(DEFAULT, GROUP, READ))
.add(aclEntry(DEFAULT, OTHER, NONE))
.build();
replaceAclEntries(existing, ACL_SPEC_DEFAULT_TOO_LARGE);
}
|
@Override
public Map<String, Metric> getMetrics() {
final Map<String, Metric> gauges = new HashMap<>();
gauges.put("total.init", (Gauge<Long>) () -> mxBean.getHeapMemoryUsage().getInit() +
mxBean.getNonHeapMemoryUsage().getInit());
gauges.put("total.used", (Gauge<Long>) () -> mxBean.getHeapMemoryUsage().getUsed() +
mxBean.getNonHeapMemoryUsage().getUsed());
gauges.put("total.max", (Gauge<Long>) () -> mxBean.getNonHeapMemoryUsage().getMax() == -1 ?
-1 : mxBean.getHeapMemoryUsage().getMax() + mxBean.getNonHeapMemoryUsage().getMax());
gauges.put("total.committed", (Gauge<Long>) () -> mxBean.getHeapMemoryUsage().getCommitted() +
mxBean.getNonHeapMemoryUsage().getCommitted());
gauges.put("heap.init", (Gauge<Long>) () -> mxBean.getHeapMemoryUsage().getInit());
gauges.put("heap.used", (Gauge<Long>) () -> mxBean.getHeapMemoryUsage().getUsed());
gauges.put("heap.max", (Gauge<Long>) () -> mxBean.getHeapMemoryUsage().getMax());
gauges.put("heap.committed", (Gauge<Long>) () -> mxBean.getHeapMemoryUsage().getCommitted());
gauges.put("heap.usage", new RatioGauge() {
@Override
protected Ratio getRatio() {
final MemoryUsage usage = mxBean.getHeapMemoryUsage();
return Ratio.of(usage.getUsed(), usage.getMax());
}
});
gauges.put("non-heap.init", (Gauge<Long>) () -> mxBean.getNonHeapMemoryUsage().getInit());
gauges.put("non-heap.used", (Gauge<Long>) () -> mxBean.getNonHeapMemoryUsage().getUsed());
gauges.put("non-heap.max", (Gauge<Long>) () -> mxBean.getNonHeapMemoryUsage().getMax());
gauges.put("non-heap.committed", (Gauge<Long>) () -> mxBean.getNonHeapMemoryUsage().getCommitted());
gauges.put("non-heap.usage", new RatioGauge() {
@Override
protected Ratio getRatio() {
final MemoryUsage usage = mxBean.getNonHeapMemoryUsage();
return Ratio.of(usage.getUsed(), usage.getMax() == -1 ? usage.getCommitted() : usage.getMax());
}
});
for (final MemoryPoolMXBean pool : memoryPools) {
final String poolName = name("pools", WHITESPACE.matcher(pool.getName()).replaceAll("-"));
gauges.put(name(poolName, "usage"), new RatioGauge() {
@Override
protected Ratio getRatio() {
MemoryUsage usage = pool.getUsage();
return Ratio.of(usage.getUsed(),
usage.getMax() == -1 ? usage.getCommitted() : usage.getMax());
}
});
gauges.put(name(poolName, "max"), (Gauge<Long>) () -> pool.getUsage().getMax());
gauges.put(name(poolName, "used"), (Gauge<Long>) () -> pool.getUsage().getUsed());
gauges.put(name(poolName, "committed"), (Gauge<Long>) () -> pool.getUsage().getCommitted());
// Only register GC usage metrics if the memory pool supports usage statistics.
if (pool.getCollectionUsage() != null) {
gauges.put(name(poolName, "used-after-gc"), (Gauge<Long>) () ->
pool.getCollectionUsage().getUsed());
}
gauges.put(name(poolName, "init"), (Gauge<Long>) () -> pool.getUsage().getInit());
}
return Collections.unmodifiableMap(gauges);
}
|
@Test
public void hasAGaugeForMemoryPoolUsage() {
final Gauge gauge = (Gauge) gauges.getMetrics().get("pools.Big-Pool.usage");
assertThat(gauge.getValue())
.isEqualTo(0.75);
}
|
public static FileEntriesLayer extraDirectoryLayerConfiguration(
Path sourceDirectory,
AbsoluteUnixPath targetDirectory,
List<String> includes,
List<String> excludes,
Map<String, FilePermissions> extraDirectoryPermissions,
ModificationTimeProvider modificationTimeProvider)
throws IOException {
FileEntriesLayer.Builder builder =
FileEntriesLayer.builder().setName(LayerType.EXTRA_FILES.getName());
Map<PathMatcher, FilePermissions> permissionsPathMatchers = new LinkedHashMap<>();
for (Map.Entry<String, FilePermissions> entry : extraDirectoryPermissions.entrySet()) {
permissionsPathMatchers.put(
FileSystems.getDefault().getPathMatcher(GLOB_PREFIX + entry.getKey()), entry.getValue());
}
DirectoryWalker walker = new DirectoryWalker(sourceDirectory).filterRoot();
// add exclusion filters
excludes.stream()
.map(pattern -> FileSystems.getDefault().getPathMatcher(GLOB_PREFIX + pattern))
.forEach(
pathMatcher ->
walker.filter(path -> !pathMatcher.matches(sourceDirectory.relativize(path))));
// add an inclusion filter
includes.stream()
.map(pattern -> FileSystems.getDefault().getPathMatcher(GLOB_PREFIX + pattern))
.map(
pathMatcher ->
(Predicate<Path>) path -> pathMatcher.matches(sourceDirectory.relativize(path)))
.reduce((matches1, matches2) -> matches1.or(matches2))
.ifPresent(walker::filter);
// walk the source tree and add layer entries
walker.walk(
localPath -> {
AbsoluteUnixPath pathOnContainer =
targetDirectory.resolve(sourceDirectory.relativize(localPath));
Instant modificationTime = modificationTimeProvider.get(localPath, pathOnContainer);
Optional<FilePermissions> permissions =
determinePermissions(
pathOnContainer, extraDirectoryPermissions, permissionsPathMatchers);
if (permissions.isPresent()) {
builder.addEntry(localPath, pathOnContainer, permissions.get(), modificationTime);
} else {
builder.addEntry(localPath, pathOnContainer, modificationTime);
}
});
return builder.build();
}
|
@Test
public void testExtraDirectoryLayerConfiguration_globPermissions()
throws URISyntaxException, IOException {
Path extraFilesDirectory = Paths.get(Resources.getResource("core/layer").toURI());
Map<String, FilePermissions> permissionsMap =
ImmutableMap.of(
"/a",
FilePermissions.fromOctalString("123"),
"/a/*",
FilePermissions.fromOctalString("456"),
"**/bar",
FilePermissions.fromOctalString("765"));
FileEntriesLayer fileEntriesLayer =
JavaContainerBuilderHelper.extraDirectoryLayerConfiguration(
extraFilesDirectory,
AbsoluteUnixPath.get("/"),
Collections.emptyList(),
Collections.emptyList(),
permissionsMap,
(ignored1, ignored2) -> Instant.EPOCH);
assertThat(fileEntriesLayer.getEntries())
.comparingElementsUsing(EXTRACTION_PATH_OF)
.containsExactly("/a", "/a/b", "/a/b/bar", "/c", "/c/cat", "/foo");
Map<AbsoluteUnixPath, FilePermissions> expectedPermissions =
ImmutableMap.<AbsoluteUnixPath, FilePermissions>builder()
.put(AbsoluteUnixPath.get("/a"), FilePermissions.fromOctalString("123"))
.put(AbsoluteUnixPath.get("/a/b"), FilePermissions.fromOctalString("456"))
.put(AbsoluteUnixPath.get("/a/b/bar"), FilePermissions.fromOctalString("765"))
.put(AbsoluteUnixPath.get("/c"), FilePermissions.DEFAULT_FOLDER_PERMISSIONS)
.put(AbsoluteUnixPath.get("/c/cat"), FilePermissions.DEFAULT_FILE_PERMISSIONS)
.put(AbsoluteUnixPath.get("/foo"), FilePermissions.DEFAULT_FILE_PERMISSIONS)
.build();
for (FileEntry entry : fileEntriesLayer.getEntries()) {
assertThat(entry.getPermissions())
.isEqualTo(expectedPermissions.get(entry.getExtractionPath()));
}
}
|
public void execute(){
logger.debug("[" + getOperationName() + "] Starting execution of paged operation. maximum time: " + maxTime + ", maximum pages: " + maxPages);
long startTime = System.currentTimeMillis();
long executionTime = 0;
int i = 0;
int exceptionsSwallowedCount = 0;
int operationsCompleted = 0;
Set<String> exceptionsSwallowedClasses = new HashSet<String>();
while (i< maxPages && executionTime < maxTime){
Collection<T> page = fetchPage();
if(page == null || page.size() == 0){
break;
}
for (T item : page) {
try {
doOperation(item);
operationsCompleted++;
} catch (Exception e){
if(swallowExceptions){
exceptionsSwallowedCount++;
exceptionsSwallowedClasses.add(e.getClass().getName());
logger.debug("Swallowing exception " + e.getMessage(), e);
} else {
logger.debug("Rethrowing exception " + e.getMessage());
throw e;
}
}
}
i++;
executionTime = System.currentTimeMillis() - startTime;
}
finalReport(operationsCompleted, exceptionsSwallowedCount, exceptionsSwallowedClasses);
}
|
@Test(timeout = 1000L)
public void execute_npage(){
int n = 7;
CountingPageOperation op = new CountingPageOperation(n,Long.MAX_VALUE);
op.execute();
assertEquals(n*10L, op.counter);
}
|
public Collection<QualifiedTable> getSingleTables(final Collection<QualifiedTable> qualifiedTables) {
Collection<QualifiedTable> result = new LinkedList<>();
for (QualifiedTable each : qualifiedTables) {
Collection<DataNode> dataNodes = singleTableDataNodes.getOrDefault(each.getTableName().toLowerCase(), new LinkedList<>());
if (!dataNodes.isEmpty() && containsDataNode(each, dataNodes)) {
result.add(each);
}
}
return result;
}
|
@Test
void assertGetSingleTables() {
SingleRule singleRule = new SingleRule(ruleConfig, DefaultDatabase.LOGIC_NAME, new H2DatabaseType(), dataSourceMap, Collections.singleton(mock(ShardingSphereRule.class, RETURNS_DEEP_STUBS)));
Collection<QualifiedTable> tableNames = new LinkedList<>();
tableNames.add(new QualifiedTable(DefaultDatabase.LOGIC_NAME, "employee"));
assertThat(singleRule.getSingleTables(tableNames).iterator().next().getSchemaName(), is(DefaultDatabase.LOGIC_NAME));
assertThat(singleRule.getSingleTables(tableNames).iterator().next().getTableName(), is("employee"));
}
|
@VisibleForTesting
public static JobGraph createJobGraph(StreamGraph streamGraph) {
return new StreamingJobGraphGenerator(
Thread.currentThread().getContextClassLoader(),
streamGraph,
null,
Runnable::run)
.createJobGraph();
}
|
@Test
void testEnabledUnalignedCheckAndDisabledCheckpointing() {
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.fromData(0).print();
StreamGraph streamGraph = env.getStreamGraph();
assertThat(streamGraph.getCheckpointConfig().isCheckpointingEnabled())
.withFailMessage("Checkpointing enabled")
.isFalse();
env.getCheckpointConfig().enableUnalignedCheckpoints(true);
JobGraph jobGraph = StreamingJobGraphGenerator.createJobGraph(streamGraph);
List<JobVertex> verticesSorted = jobGraph.getVerticesSortedTopologicallyFromSources();
StreamConfig streamConfig = new StreamConfig(verticesSorted.get(0).getConfiguration());
assertThat(streamConfig.getCheckpointMode()).isEqualTo(CheckpointingMode.AT_LEAST_ONCE);
assertThat(streamConfig.isUnalignedCheckpointsEnabled()).isFalse();
}
|
public static <K> PerKeyDigest<K> perKey() {
return PerKeyDigest.<K>builder().build();
}
|
@Test
public void perKey() {
PCollection<KV<Double, Double>> col =
tp.apply(Create.of(stream))
.apply(WithKeys.of(1))
.apply(TDigestQuantiles.<Integer>perKey().withCompression(compression))
.apply(Values.create())
.apply(ParDo.of(new RetrieveQuantiles(quantiles)));
PAssert.that("Verify Accuracy", col).satisfies(new VerifyAccuracy());
tp.run();
}
|
public void clear()
{
data.clear();
inverse.clear();
}
|
@Test
public void testClear()
{
map.clear();
assertSize(0);
}
|
public MessagesRequestSpec simpleQueryParamsToFullRequestSpecification(final String query,
final Set<String> streams,
final String timerangeKeyword,
final List<String> fields,
final String sort,
final SortSpec.Direction sortOrder,
final int from,
final int size) {
return new MessagesRequestSpec(query,
streams,
timerangeParser.parseTimeRange(timerangeKeyword),
sort,
sortOrder,
from,
size,
fields);
}
|
@Test
void throwsExceptionOnEmptyGroups() {
assertThrows(IllegalArgumentException.class, () -> toTest.simpleQueryParamsToFullRequestSpecification("*",
Set.of(),
"42d",
List.of(),
List.of("avg:joe")));
}
|
public DoubleArrayAsIterable usingTolerance(double tolerance) {
return new DoubleArrayAsIterable(tolerance(tolerance), iterableSubject());
}
|
@Test
public void usingTolerance_contains_failure() {
expectFailureWhenTestingThat(array(1.1, INTOLERABLE_2POINT2, 3.3))
.usingTolerance(DEFAULT_TOLERANCE)
.contains(2.2);
assertFailureKeys("value of", "expected to contain", "testing whether", "but was");
assertFailureValue("value of", "array.asList()");
assertFailureValue("expected to contain", "2.2");
assertFailureValue(
"testing whether",
"actual element is a finite number within " + DEFAULT_TOLERANCE + " of expected element");
assertFailureValue("but was", "[1.1, " + INTOLERABLE_2POINT2 + ", 3.3]");
}
|
public static Object convertAvroFormat(
FieldType beamFieldType, Object avroValue, BigQueryUtils.ConversionOptions options) {
TypeName beamFieldTypeName = beamFieldType.getTypeName();
if (avroValue == null) {
if (beamFieldType.getNullable()) {
return null;
} else {
throw new IllegalArgumentException(String.format("Field %s not nullable", beamFieldType));
}
}
switch (beamFieldTypeName) {
case BYTE:
case INT16:
case INT32:
case INT64:
case FLOAT:
case DOUBLE:
case STRING:
case BYTES:
case BOOLEAN:
return convertAvroPrimitiveTypes(beamFieldTypeName, avroValue);
case DATETIME:
// Expecting value in microseconds.
switch (options.getTruncateTimestamps()) {
case TRUNCATE:
return truncateToMillis(avroValue);
case REJECT:
return safeToMillis(avroValue);
default:
throw new IllegalArgumentException(
String.format(
"Unknown timestamp truncation option: %s", options.getTruncateTimestamps()));
}
case DECIMAL:
return convertAvroNumeric(avroValue);
case ARRAY:
return convertAvroArray(beamFieldType, avroValue, options);
case LOGICAL_TYPE:
LogicalType<?, ?> logicalType = beamFieldType.getLogicalType();
assert logicalType != null;
String identifier = logicalType.getIdentifier();
if (SqlTypes.DATE.getIdentifier().equals(identifier)) {
return convertAvroDate(avroValue);
} else if (SqlTypes.TIME.getIdentifier().equals(identifier)) {
return convertAvroTime(avroValue);
} else if (SqlTypes.DATETIME.getIdentifier().equals(identifier)) {
return convertAvroDateTime(avroValue);
} else if (SQL_DATE_TIME_TYPES.contains(identifier)) {
switch (options.getTruncateTimestamps()) {
case TRUNCATE:
return truncateToMillis(avroValue);
case REJECT:
return safeToMillis(avroValue);
default:
throw new IllegalArgumentException(
String.format(
"Unknown timestamp truncation option: %s", options.getTruncateTimestamps()));
}
} else if (logicalType instanceof PassThroughLogicalType) {
return convertAvroFormat(logicalType.getBaseType(), avroValue, options);
} else {
throw new RuntimeException("Unknown logical type " + identifier);
}
case ROW:
Schema rowSchema = beamFieldType.getRowSchema();
if (rowSchema == null) {
throw new IllegalArgumentException("Nested ROW missing row schema");
}
GenericData.Record record = (GenericData.Record) avroValue;
return toBeamRow(record, rowSchema, options);
case MAP:
return convertAvroRecordToMap(beamFieldType, avroValue, options);
default:
throw new RuntimeException(
"Does not support converting unknown type value: " + beamFieldTypeName);
}
}
|
@Test
public void testMilliPrecisionOk() {
long millis = 123456789L;
assertThat(
BigQueryUtils.convertAvroFormat(FieldType.DATETIME, millis * 1000, REJECT_OPTIONS),
equalTo(new Instant(millis)));
}
|
public static InetSocketAddress createResolved(String hostname, int port) {
return createInetSocketAddress(hostname, port, true);
}
|
@Test
void createResolvedBadValues() {
assertThatExceptionOfType(NullPointerException.class)
.isThrownBy(() -> AddressUtils.createResolved(null, 0))
.withMessage("hostname");
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> AddressUtils.createResolved("hostname", -1))
.withMessage("port out of range:-1");
}
|
private static GuardedByExpression bind(JCTree.JCExpression exp, BinderContext context) {
GuardedByExpression expr = BINDER.visit(exp, context);
checkGuardedBy(expr != null, String.valueOf(exp));
checkGuardedBy(expr.kind() != Kind.TYPE_LITERAL, "Raw type literal: %s", exp);
return expr;
}
|
@Test
public void method() {
assertThat(
bind(
"Test",
"s.f.g().f.g().lock",
forSourceLines(
"threadsafety/Test.java",
"package threadsafety;",
"import javax.annotation.concurrent.GuardedBy;",
"class Super {",
" final Super f = null;",
" Super g() { return null; }",
" final Object lock = new Object();",
"}",
"class Test {",
" final Super s = null;",
"}")))
.isEqualTo(
"(SELECT (SELECT (SELECT (SELECT (SELECT (SELECT " + "(THIS) s) f) g()) f) g()) lock)");
}
|
public static @Nullable Type inferType(@Nullable Object value) {
return Type.tryInferFrom(value);
}
|
@Test
public void testKnownTypeInference() {
assertEquals(DisplayData.Type.INTEGER, DisplayData.inferType(1234));
assertEquals(DisplayData.Type.INTEGER, DisplayData.inferType(1234L));
assertEquals(DisplayData.Type.FLOAT, DisplayData.inferType(12.3));
assertEquals(DisplayData.Type.FLOAT, DisplayData.inferType(12.3f));
assertEquals(DisplayData.Type.BOOLEAN, DisplayData.inferType(true));
assertEquals(DisplayData.Type.TIMESTAMP, DisplayData.inferType(Instant.now()));
assertEquals(DisplayData.Type.DURATION, DisplayData.inferType(Duration.millis(1234)));
assertEquals(DisplayData.Type.JAVA_CLASS, DisplayData.inferType(DisplayDataTest.class));
assertEquals(DisplayData.Type.STRING, DisplayData.inferType("hello world"));
assertEquals(null, DisplayData.inferType(null));
assertEquals(null, DisplayData.inferType(new Object() {}));
}
|
@Override
public DescribeProducersResult describeProducers(Collection<TopicPartition> topicPartitions, DescribeProducersOptions options) {
AdminApiFuture.SimpleAdminApiFuture<TopicPartition, DescribeProducersResult.PartitionProducerState> future =
DescribeProducersHandler.newFuture(topicPartitions);
DescribeProducersHandler handler = new DescribeProducersHandler(options, logContext);
invokeDriver(handler, future, options.timeoutMs);
return new DescribeProducersResult(future.all());
}
|
@Test
public void testDescribeProducers() throws Exception {
try (AdminClientUnitTestEnv env = mockClientEnv()) {
TopicPartition topicPartition = new TopicPartition("foo", 0);
Node leader = env.cluster().nodes().iterator().next();
expectMetadataRequest(env, topicPartition, leader);
List<ProducerState> expected = asList(
new ProducerState(12345L, 15, 30, env.time().milliseconds(),
OptionalInt.of(99), OptionalLong.empty()),
new ProducerState(12345L, 15, 30, env.time().milliseconds(),
OptionalInt.empty(), OptionalLong.of(23423L))
);
DescribeProducersResponse response = buildDescribeProducersResponse(
topicPartition,
expected
);
env.kafkaClient().prepareResponseFrom(
request -> request instanceof DescribeProducersRequest,
response,
leader
);
DescribeProducersResult result = env.adminClient().describeProducers(singleton(topicPartition));
KafkaFuture<DescribeProducersResult.PartitionProducerState> partitionFuture =
result.partitionResult(topicPartition);
assertEquals(new HashSet<>(expected), new HashSet<>(partitionFuture.get().activeProducers()));
}
}
|
public Map<String, UserAuth> getUsers() { return users; }
|
@Test
public void testPaths() {
Map<String, UserAuth> users = config.getUsers();
UserAuth user = users.get("user1");
Assert.assertEquals("user1", user.getUsername());
Assert.assertEquals("user1pass", user.getPassword());
Assert.assertEquals(1, user.getPaths().size());
Assert.assertEquals("/v1/address", user.getPaths().get(0));
}
|
@Override
public void info(String msg) {
logger.info(msg);
logInfoToJobDashboard(msg);
}
|
@Test
void testInfoLoggingWithoutJob() {
jobRunrDashboardLogger.info("simple message");
verify(slfLogger).info("simple message");
}
|
public static Criterion matchIPDscp(byte ipDscp) {
return new IPDscpCriterion(ipDscp);
}
|
@Test
public void testMatchIPDscpMethod() {
Criterion matchIPDscp = Criteria.matchIPDscp(ipDscp1);
IPDscpCriterion ipDscpCriterion =
checkAndConvert(matchIPDscp,
Criterion.Type.IP_DSCP,
IPDscpCriterion.class);
assertThat(ipDscpCriterion.ipDscp(), is(equalTo(ipDscp1)));
}
|
@Override
public PermissionTicket createTicket(ResourceSet resourceSet, Set<String> scopes) {
// check to ensure that the scopes requested are a subset of those in the resource set
if (!scopeService.scopesMatch(resourceSet.getScopes(), scopes)) {
throw new InsufficientScopeException("Scopes of resource set are not enough for requested permission.");
}
Permission perm = new Permission();
perm.setResourceSet(resourceSet);
perm.setScopes(scopes);
PermissionTicket ticket = new PermissionTicket();
ticket.setPermission(perm);
ticket.setTicket(UUID.randomUUID().toString());
ticket.setExpiration(new Date(System.currentTimeMillis() + permissionExpirationSeconds * 1000L));
return repository.save(ticket);
}
|
@Test
public void testCreate_uuid() {
PermissionTicket perm = permissionService.createTicket(rs1, scopes1);
// we expect this to be a UUID
UUID uuid = UUID.fromString(perm.getTicket());
assertNotNull(uuid);
}
|
public int getKafkaSocketTimeout() {
return _kafkaSocketTimeout;
}
|
@Test
public void testGetKafkaSocketTimeout() {
// test default
KafkaPartitionLevelStreamConfig config = getStreamConfig("topic", "host1", "", null);
Assert.assertEquals(KafkaStreamConfigProperties.LowLevelConsumer.KAFKA_SOCKET_TIMEOUT_DEFAULT,
config.getKafkaSocketTimeout());
config = getStreamConfig("topic", "host1", "", "");
Assert.assertEquals(KafkaStreamConfigProperties.LowLevelConsumer.KAFKA_SOCKET_TIMEOUT_DEFAULT,
config.getKafkaSocketTimeout());
config = getStreamConfig("topic", "host1", "", "bad value");
Assert.assertEquals(KafkaStreamConfigProperties.LowLevelConsumer.KAFKA_SOCKET_TIMEOUT_DEFAULT,
config.getKafkaSocketTimeout());
// correct config
config = getStreamConfig("topic", "host1", "", "100");
Assert.assertEquals(100, config.getKafkaSocketTimeout());
}
|
@InvokeOnHeader(Web3jConstants.SHH_POST)
void shhPost(Message message) throws IOException {
String fromAddress = message.getHeader(Web3jConstants.FROM_ADDRESS, configuration::getFromAddress, String.class);
String toAddress = message.getHeader(Web3jConstants.TO_ADDRESS, configuration::getToAddress, String.class);
List<String> topics = message.getHeader(Web3jConstants.TOPICS, configuration::getTopics, List.class);
String data = message.getHeader(Web3jConstants.DATA, configuration::getData, String.class);
BigInteger priority = message.getHeader(Web3jConstants.PRIORITY, configuration::getPriority, BigInteger.class);
BigInteger ttl = message.getHeader(Web3jConstants.TTL, configuration::getTtl, BigInteger.class);
org.web3j.protocol.core.methods.request.ShhPost shhPost
= new org.web3j.protocol.core.methods.request.ShhPost(fromAddress, toAddress, topics, data, priority, ttl);
Request<?, ShhPost> request = web3j.shhPost(shhPost);
setRequestId(message, request);
ShhPost response = request.send();
boolean hasError = checkForError(message, response);
if (!hasError) {
message.setBody(response.messageSent());
}
}
|
@Test
public void shhPostTest() throws Exception {
ShhPost response = Mockito.mock(ShhPost.class);
Mockito.when(mockWeb3j.shhPost(any())).thenReturn(request);
Mockito.when(request.send()).thenReturn(response);
Mockito.when(response.messageSent()).thenReturn(Boolean.TRUE);
Exchange exchange = createExchangeWithBodyAndHeader(null, OPERATION, Web3jConstants.SHH_POST);
template.send(exchange);
Boolean body = exchange.getIn().getBody(Boolean.class);
assertTrue(body);
}
|
public void setTemplateEntriesForChild(CapacitySchedulerConfiguration conf,
QueuePath childQueuePath) {
setTemplateEntriesForChild(conf, childQueuePath, false);
}
|
@Test
public void testIgnoredWhenNoParent() {
conf.set(getTemplateKey(ROOT, "capacity"), "6w");
AutoCreatedQueueTemplate template =
new AutoCreatedQueueTemplate(conf, ROOT);
template.setTemplateEntriesForChild(conf, ROOT);
Assert.assertEquals("weight is set", -1f,
conf.getNonLabeledQueueWeight(ROOT), 10e-6);
}
|
public JmxCollector register() {
return register(PrometheusRegistry.defaultRegistry);
}
|
@Test
public void tabularDataCompositeKeyTest() throws Exception {
JmxCollector jc = new JmxCollector("---").register(prometheusRegistry);
assertEquals(
1,
getSampleValue(
"org_exist_management_exist_ProcessReport_RunningQueries_id",
new String[] {"key_id", "key_path"},
new String[] {"1", "/db/query1.xq"}),
.001);
assertEquals(
2,
getSampleValue(
"org_exist_management_exist_ProcessReport_RunningQueries_id",
new String[] {"key_id", "key_path"},
new String[] {"2", "/db/query2.xq"}),
.001);
}
|
@Override public final Object unwrap() {
return response;
}
|
@Test void unwrap() {
HttpServerResponse wrapper = HttpServletResponseWrapper.create(request, response, null);
assertThat(wrapper.unwrap())
.isEqualTo(response);
}
|
@Override
public void execute(ComputationStep.Context context) {
new PathAwareCrawler<>(
FormulaExecutorComponentVisitor.newBuilder(metricRepository, measureRepository)
.buildFor(List.of(duplicationFormula)))
.visit(treeRootHolder.getRoot());
}
|
@Test
public void compute_duplicated_lines_counts_lines_from_original_and_InnerDuplicate() {
TextBlock original = new TextBlock(1, 5);
duplicationRepository.addDuplication(FILE_1_REF, original, new TextBlock(10, 11));
setNewLines(FILE_1);
underTest.execute(new TestComputationStepContext());
assertRawMeasureValue(FILE_1_REF, NEW_DUPLICATED_LINES_KEY, 6);
}
|
public static Ip4Address valueOf(int value) {
byte[] bytes =
ByteBuffer.allocate(INET_BYTE_LENGTH).putInt(value).array();
return new Ip4Address(bytes);
}
|
@Test(expected = IllegalArgumentException.class)
public void testInvalidValueOfEmptyString() {
Ip4Address ipAddress;
String fromString = "";
ipAddress = Ip4Address.valueOf(fromString);
}
|
@Override
public ContinuousEnumerationResult planSplits(IcebergEnumeratorPosition lastPosition) {
table.refresh();
if (lastPosition != null) {
return discoverIncrementalSplits(lastPosition);
} else {
return discoverInitialSplits();
}
}
|
@Test
public void testTableScanThenIncrementalWithNonEmptyTable() throws Exception {
appendTwoSnapshots();
ScanContext scanContext =
ScanContext.builder()
.startingStrategy(StreamingStartingStrategy.TABLE_SCAN_THEN_INCREMENTAL)
.build();
ContinuousSplitPlannerImpl splitPlanner =
new ContinuousSplitPlannerImpl(TABLE_RESOURCE.tableLoader().clone(), scanContext, null);
ContinuousEnumerationResult initialResult = splitPlanner.planSplits(null);
assertThat(initialResult.fromPosition()).isNull();
assertThat(initialResult.toPosition().snapshotId().longValue())
.isEqualTo(snapshot2.snapshotId());
assertThat(initialResult.toPosition().snapshotTimestampMs().longValue())
.isEqualTo(snapshot2.timestampMillis());
assertThat(initialResult.splits()).hasSize(1);
IcebergSourceSplit split = Iterables.getOnlyElement(initialResult.splits());
assertThat(split.task().files()).hasSize(2);
Set<String> discoveredFiles =
split.task().files().stream()
.map(fileScanTask -> fileScanTask.file().path().toString())
.collect(Collectors.toSet());
Set<String> expectedFiles =
ImmutableSet.of(dataFile1.path().toString(), dataFile2.path().toString());
assertThat(discoveredFiles).containsExactlyInAnyOrderElementsOf(expectedFiles);
IcebergEnumeratorPosition lastPosition = initialResult.toPosition();
for (int i = 0; i < 3; ++i) {
lastPosition = verifyOneCycle(splitPlanner, lastPosition).lastPosition;
}
}
|
@Override
public EventPublisher apply(final Class<? extends Event> eventType, final Integer maxQueueSize) {
// Like ClientEvent$ClientChangeEvent cache by ClientEvent
Class<? extends Event> cachedEventType =
eventType.isMemberClass() ? (Class<? extends Event>) eventType.getEnclosingClass() : eventType;
return publisher.computeIfAbsent(cachedEventType, eventClass -> {
NamingEventPublisher result = new NamingEventPublisher();
result.init(eventClass, maxQueueSize);
return result;
});
}
|
@Test
void testApply() {
NamingEventPublisherFactory.getInstance().apply(TestEvent.TestEvent1.class, Byte.SIZE);
NamingEventPublisherFactory.getInstance().apply(TestEvent.TestEvent2.class, Byte.SIZE);
NamingEventPublisherFactory.getInstance().apply(TestEvent.class, Byte.SIZE);
String expectedStatus =
"Naming event publisher statues:\n" + "\tPublisher TestEvent : shutdown=false, queue= 0/8 \n";
assertThat(NamingEventPublisherFactory.getInstance().getAllPublisherStatues(), is(expectedStatus));
}
|
@SuppressWarnings("MethodMayBeStatic")
@Udf(description = "The 2 input points should be specified as (lat, lon) pairs, measured"
+ " in decimal degrees. An optional fifth parameter allows to specify either \"MI\" (miles)"
+ " or \"KM\" (kilometers) as the desired unit for the output measurement. Default is KM.")
public Double geoDistance(
@UdfParameter(description = "The latitude of the first point in decimal degrees.")
final double lat1,
@UdfParameter(description = "The longitude of the first point in decimal degrees.")
final double lon1,
@UdfParameter(description = "The latitude of the second point in decimal degrees.")
final double lat2,
@UdfParameter(description = "The longitude of the second point in decimal degrees.")
final double lon2,
@UdfParameter(description = "The units for the return value. Either MILES or KM.")
final String units
) {
validateLatLonValues(lat1, lon1, lat2, lon2);
final double chosenRadius = selectEarthRadiusToUse(units);
final double deltaLat = Math.toRadians(lat2 - lat1);
final double deltaLon = Math.toRadians(lon2 - lon1);
final double lat1Radians = Math.toRadians(lat1);
final double lat2Radians = Math.toRadians(lat2);
final double a =
haversin(deltaLat) + haversin(deltaLon) * Math.cos(lat1Radians) * Math.cos(lat2Radians);
final double distanceInRadians = 2 * Math.asin(Math.sqrt(a));
return distanceInRadians * chosenRadius;
}
|
@Test
public void shouldFailOutOfBoundsCoordinates() {
// When:
final Exception e = assertThrows(
KsqlFunctionException.class,
() -> distanceUdf.geoDistance(90.1, -122.1663, -91.5257, -0.1122)
);
// Then:
assertThat(e.getMessage(), containsString(
"valid latitude values for GeoDistance function are"));
}
|
public double d(int[] x, int[] y) {
if (x.length != y.length)
throw new IllegalArgumentException(String.format("Arrays have different length: x[%d], y[%d]", x.length, y.length));
double dist = 0.0;
if (weight == null) {
for (int i = 0; i < x.length; i++) {
dist += Math.abs(x[i] - y[i]);
}
} else {
if (x.length != weight.length)
throw new IllegalArgumentException(String.format("Input vectors and weight vector have different length: %d, %d", x.length, weight.length));
for (int i = 0; i < x.length; i++) {
dist += weight[i] * Math.abs(x[i] - y[i]);
}
}
return dist;
}
|
@Test
public void testDistanceDouble() {
System.out.println("distance");
double[] x = {-2.1968219, -0.9559913, -0.0431738, 1.0567679, 0.3853515};
double[] y = {-1.7781325, -0.6659839, 0.9526148, -0.9460919, -0.3925300};
assertEquals(4.485227, new ManhattanDistance().d(x, y), 1E-6);
}
|
public static java.util.Date convertToDate(Schema schema, Object value) {
if (value == null) {
throw new DataException("Unable to convert a null value to a schema that requires a value");
}
return convertToDate(Date.SCHEMA, schema, value);
}
|
@Test
public void shouldConvertDateValues() {
java.util.Date current = new java.util.Date();
long currentMillis = current.getTime() % MILLIS_PER_DAY;
long days = current.getTime() / MILLIS_PER_DAY;
// java.util.Date - just copy
java.util.Date d1 = Values.convertToDate(Date.SCHEMA, current);
assertEquals(current, d1);
// java.util.Date as a Timestamp - discard the day's milliseconds and keep the date
java.util.Date currentDate = new java.util.Date(current.getTime() - currentMillis);
d1 = Values.convertToDate(Timestamp.SCHEMA, currentDate);
assertEquals(currentDate, d1);
// ISO8601 strings - currently broken because tokenization breaks at colon
// Days as string
java.util.Date d3 = Values.convertToDate(Date.SCHEMA, Long.toString(days));
assertEquals(currentDate, d3);
// Days as long
java.util.Date d4 = Values.convertToDate(Date.SCHEMA, days);
assertEquals(currentDate, d4);
}
|
public static VersionRange parse(String rangeString) {
validateRangeString(rangeString);
Inclusiveness minVersionInclusiveness =
rangeString.startsWith("[") ? Inclusiveness.INCLUSIVE : Inclusiveness.EXCLUSIVE;
Inclusiveness maxVersionInclusiveness =
rangeString.endsWith("]") ? Inclusiveness.INCLUSIVE : Inclusiveness.EXCLUSIVE;
int commaIndex = rangeString.indexOf(',');
String minVersionString = rangeString.substring(1, commaIndex).trim();
Version minVersion;
if (minVersionString.isEmpty()) {
minVersionInclusiveness = Inclusiveness.EXCLUSIVE;
minVersion = Version.minimum();
} else {
minVersion = Version.fromString(minVersionString);
}
String maxVersionString =
rangeString.substring(commaIndex + 1, rangeString.length() - 1).trim();
Version maxVersion;
if (maxVersionString.isEmpty()) {
maxVersionInclusiveness = Inclusiveness.EXCLUSIVE;
maxVersion = Version.maximum();
} else {
maxVersion = Version.fromString(maxVersionString);
}
if (!minVersion.isLessThan(maxVersion)) {
throw new IllegalArgumentException(
String.format(
"Min version in range must be less than max version in range, got '%s'",
rangeString));
}
return builder()
.setMinVersion(minVersion)
.setMinVersionInclusiveness(minVersionInclusiveness)
.setMaxVersion(maxVersion)
.setMaxVersionInclusiveness(maxVersionInclusiveness)
.build();
}
|
@Test
public void parse_withRangeNotEndingWithParenthesis_throwsIllegalArgumentException() {
IllegalArgumentException exception =
assertThrows(IllegalArgumentException.class, () -> VersionRange.parse("(,1.0"));
assertThat(exception)
.hasMessageThat()
.isEqualTo("Version range must end with ']' or ')', got '(,1.0'");
}
|
@Override
public ChannelFuture writeFrame(ChannelHandlerContext ctx, byte frameType, int streamId,
Http2Flags flags, ByteBuf payload, ChannelPromise promise) {
SimpleChannelPromiseAggregator promiseAggregator =
new SimpleChannelPromiseAggregator(promise, ctx.channel(), ctx.executor());
try {
verifyStreamOrConnectionId(streamId, STREAM_ID);
ByteBuf buf = ctx.alloc().buffer(FRAME_HEADER_LENGTH);
// Assume nothing below will throw until buf is written. That way we don't have to take care of ownership
// in the catch block.
writeFrameHeaderInternal(buf, payload.readableBytes(), frameType, flags, streamId);
ctx.write(buf, promiseAggregator.newPromise());
} catch (Throwable t) {
try {
payload.release();
} finally {
promiseAggregator.setFailure(t);
promiseAggregator.doneAllocatingPromises();
}
return promiseAggregator;
}
try {
ctx.write(payload, promiseAggregator.newPromise());
} catch (Throwable t) {
promiseAggregator.setFailure(t);
}
return promiseAggregator.doneAllocatingPromises();
}
|
@Test
public void writeFrameZeroPayload() throws Exception {
frameWriter.writeFrame(ctx, (byte) 0xf, 0, new Http2Flags(), Unpooled.EMPTY_BUFFER, promise);
byte[] expectedFrameBytes = {
(byte) 0x00, (byte) 0x00, (byte) 0x00, // payload length
(byte) 0x0f, // payload type
(byte) 0x00, // flags
(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00 // stream id
};
expectedOutbound = Unpooled.wrappedBuffer(expectedFrameBytes);
assertEquals(expectedOutbound, outbound);
}
|
public static <T extends PipelineOptions> T validate(Class<T> klass, PipelineOptions options) {
return validate(klass, options, false);
}
|
@Test
public void testWhenOptionIsDefinedInMultipleSuperInterfacesMeetsGroupRequirement() {
RightOptions rightOpts = PipelineOptionsFactory.as(RightOptions.class);
rightOpts.setFoo("true");
rightOpts.setBoth("bar");
LeftOptions leftOpts = PipelineOptionsFactory.as(LeftOptions.class);
leftOpts.setFoo("Untrue");
leftOpts.setBoth("Raise the");
rightOpts.setRunner(CrashingRunner.class);
leftOpts.setRunner(CrashingRunner.class);
PipelineOptionsValidator.validate(JoinedOptions.class, rightOpts);
PipelineOptionsValidator.validate(JoinedOptions.class, leftOpts);
}
|
@Override
public double calcDist3D(double fromLat, double fromLon, double fromHeight,
double toLat, double toLon, double toHeight) {
double eleDelta = hasElevationDiff(fromHeight, toHeight) ? (toHeight - fromHeight) : 0;
double len = calcDist(fromLat, fromLon, toLat, toLon);
return Math.sqrt(eleDelta * eleDelta + len * len);
}
|
@Test
public void testDistance3dEarthNaN() {
DistanceCalc distCalc = new DistanceCalcEarth();
assertEquals(0, distCalc.calcDist3D(
0, 0, 0,
0, 0, Double.NaN
), 1e-6);
assertEquals(0, distCalc.calcDist3D(
0, 0, Double.NaN,
0, 0, 10
), 1e-6);
assertEquals(0, distCalc.calcDist3D(
0, 0, Double.NaN,
0, 0, Double.NaN
), 1e-6);
}
|
static String encodeHex(byte[] bytes) {
final char[] hex = new char[bytes.length * 2];
int i = 0;
for (byte b : bytes) {
hex[i++] = HEX_DIGITS[(b >> 4) & 0x0f];
hex[i++] = HEX_DIGITS[b & 0x0f];
}
return String.valueOf(hex);
}
|
@Test
public void encodeHex_Success() throws Exception {
byte[] input = {(byte) 0xFF, 0x00, (byte) 0xA5, 0x5A, 0x12, 0x23};
String expected = "ff00a55a1223";
assertEquals("Encoded hex should match expected",
PubkeyUtils.encodeHex(input), expected);
}
|
@Override
public String doLayout(ILoggingEvent event) {
StringWriter output = new StringWriter();
try (JsonWriter json = new JsonWriter(output)) {
json.beginObject();
if (!"".equals(nodeName)) {
json.name("nodename").value(nodeName);
}
json.name("process").value(processKey);
for (Map.Entry<String, String> entry : event.getMDCPropertyMap().entrySet()) {
if (entry.getValue() != null && !exclusions.contains(entry.getKey())) {
json.name(entry.getKey()).value(entry.getValue());
}
}
json
.name("timestamp").value(DATE_FORMATTER.format(Instant.ofEpochMilli(event.getTimeStamp())))
.name("severity").value(event.getLevel().toString())
.name("logger").value(event.getLoggerName())
.name("message").value(NEWLINE_REGEXP.matcher(event.getFormattedMessage()).replaceAll("\r"));
IThrowableProxy tp = event.getThrowableProxy();
if (tp != null) {
json.name("stacktrace").beginArray();
int nbOfTabs = 0;
while (tp != null) {
printFirstLine(json, tp, nbOfTabs);
render(json, tp, nbOfTabs);
tp = tp.getCause();
nbOfTabs++;
}
json.endArray();
}
json.endObject();
} catch (Exception e) {
e.printStackTrace();
throw new IllegalStateException("BUG - fail to create JSON", e);
}
output.write(System.lineSeparator());
return output.toString();
}
|
@Test
public void test_simple_log() {
LoggingEvent event = new LoggingEvent("org.foundation.Caller", (Logger) LoggerFactory.getLogger("the.logger"), Level.WARN, "the message", null, new Object[0]);
String log = underTest.doLayout(event);
JsonLog json = new Gson().fromJson(log, JsonLog.class);
assertThat(json.process).isEqualTo("web");
assertThat(json.timestamp).isEqualTo(DATE_FORMATTER.format(Instant.ofEpochMilli(event.getTimeStamp())));
assertThat(json.severity).isEqualTo("WARN");
assertThat(json.logger).isEqualTo("the.logger");
assertThat(json.message).isEqualTo("the message");
assertThat(json.stacktrace).isNull();
assertThat(json.fromMdc).isNull();
assertThat(json.nodename).isNull();
}
|
@Override
public void close(RemoteInputChannel inputChannel) throws IOException {
clientHandler.removeInputChannel(inputChannel);
if (closeReferenceCounter.updateAndGet(count -> Math.max(count - 1, 0)) == 0
&& !canBeReused()) {
closeConnection();
} else {
clientHandler.cancelRequestFor(inputChannel.getInputChannelId());
}
}
|
@TestTemplate
void testDoublePartitionRequest() throws Exception {
final CreditBasedPartitionRequestClientHandler handler =
new CreditBasedPartitionRequestClientHandler();
final EmbeddedChannel channel = new EmbeddedChannel(handler);
final PartitionRequestClient client =
createPartitionRequestClient(channel, handler, connectionReuseEnabled);
final int numExclusiveBuffers = 2;
final NetworkBufferPool networkBufferPool = new NetworkBufferPool(10, 32);
final SingleInputGate inputGate = createSingleInputGate(1, networkBufferPool);
final RemoteInputChannel inputChannel = createRemoteInputChannel(inputGate, client);
try {
inputGate.setInputChannels(inputChannel);
final BufferPool bufferPool = networkBufferPool.createBufferPool(6, 6);
inputGate.setBufferPool(bufferPool);
inputGate.setupChannels();
inputChannel.requestSubpartitions();
// The input channel should only send one partition request
assertThat(channel.isWritable()).isTrue();
Object readFromOutbound = channel.readOutbound();
assertThat(readFromOutbound).isInstanceOf(PartitionRequest.class);
assertThat(((PartitionRequest) readFromOutbound).receiverId)
.isEqualTo(inputChannel.getInputChannelId());
assertThat(((PartitionRequest) readFromOutbound).credit).isEqualTo(numExclusiveBuffers);
assertThat((Object) channel.readOutbound()).isNull();
} finally {
// Release all the buffer resources
inputGate.close();
networkBufferPool.destroyAllBufferPools();
networkBufferPool.destroy();
}
}
|
public static Schema createNewSchemaFromFieldsWithReference(Schema schema, List<Schema.Field> fields) {
if (schema == null) {
throw new IllegalArgumentException("Schema must not be null");
}
Schema newSchema = Schema.createRecord(schema.getName(), schema.getDoc(), schema.getNamespace(), schema.isError());
Map<String, Object> schemaProps = Collections.emptyMap();
try {
schemaProps = schema.getObjectProps();
} catch (Exception e) {
LOG.warn("Error while getting object properties from schema: {}", schema, e);
}
for (Map.Entry<String, Object> prop : schemaProps.entrySet()) {
newSchema.addProp(prop.getKey(), prop.getValue());
}
newSchema.setFields(fields);
return newSchema;
}
|
@Test
public void testCreateNewSchemaFromFieldsWithReference_NullSchema() {
// This test should throw an IllegalArgumentException
assertThrows(IllegalArgumentException.class, () -> AvroSchemaUtils.createNewSchemaFromFieldsWithReference(null, Collections.emptyList()));
}
|
public DeleteGranularity deleteGranularity() {
String valueAsString =
confParser
.stringConf()
.option(SparkWriteOptions.DELETE_GRANULARITY)
.tableProperty(TableProperties.DELETE_GRANULARITY)
.defaultValue(TableProperties.DELETE_GRANULARITY_DEFAULT)
.parse();
return DeleteGranularity.fromString(valueAsString);
}
|
@TestTemplate
public void testDeleteGranularityDefault() {
Table table = validationCatalog.loadTable(tableIdent);
SparkWriteConf writeConf = new SparkWriteConf(spark, table, ImmutableMap.of());
DeleteGranularity value = writeConf.deleteGranularity();
assertThat(value).isEqualTo(DeleteGranularity.PARTITION);
}
|
@VisibleForTesting
public static BigDecimal average(LongDecimalWithOverflowAndLongState state, DecimalType type)
{
return average(state.getLong(), state.getOverflow(), state.getLongDecimal(), type.getScale());
}
|
@Test
public void testUnderflow()
{
addToState(state, TWO.pow(126).negate());
assertEquals(state.getLong(), 1);
assertEquals(state.getOverflow(), 0);
assertEquals(state.getLongDecimal(), unscaledDecimal(TWO.pow(126).negate()));
addToState(state, TWO.pow(126).negate());
assertEquals(state.getLong(), 2);
assertEquals(state.getOverflow(), -1);
assertEquals(UnscaledDecimal128Arithmetic.compare(state.getLongDecimal(), unscaledDecimal(0)), 0);
assertEquals(average(state, TYPE), new BigDecimal(TWO.pow(126).negate()));
}
|
@Override
public MaterializedWindowedTable windowed() {
return new KsqlMaterializedWindowedTable(inner.windowed());
}
|
@Test
public void shouldCallInnerWindowedWithCorrectParamsOnGet() {
// Given:
final MaterializedWindowedTable table = materialization.windowed();
givenNoopFilter();
when(project.apply(any(), any(), any())).thenReturn(Optional.of(transformed));
// When:
table.get(aKey, partition, windowStartBounds, windowEndBounds);
// Then:
verify(innerWindowed).get(aKey, partition, windowStartBounds, windowEndBounds, Optional.empty());
}
|
public static Schema fromTableSchema(TableSchema tableSchema) {
return fromTableSchema(tableSchema, SchemaConversionOptions.builder().build());
}
|
@Test
public void testFromTableSchema_flat() {
Schema beamSchema = BigQueryUtils.fromTableSchema(BQ_FLAT_TYPE);
assertEquals(FLAT_TYPE, beamSchema);
}
|
@Override
public List<AdminUserDO> getUserListByPostIds(Collection<Long> postIds) {
if (CollUtil.isEmpty(postIds)) {
return Collections.emptyList();
}
Set<Long> userIds = convertSet(userPostMapper.selectListByPostIds(postIds), UserPostDO::getUserId);
if (CollUtil.isEmpty(userIds)) {
return Collections.emptyList();
}
return userMapper.selectBatchIds(userIds);
}
|
@Test
public void testUserListByPostIds() {
// 准备参数
Collection<Long> postIds = asSet(10L, 20L);
// mock user1 数据
AdminUserDO user1 = randomAdminUserDO(o -> o.setPostIds(asSet(10L, 30L)));
userMapper.insert(user1);
userPostMapper.insert(new UserPostDO().setUserId(user1.getId()).setPostId(10L));
userPostMapper.insert(new UserPostDO().setUserId(user1.getId()).setPostId(30L));
// mock user2 数据
AdminUserDO user2 = randomAdminUserDO(o -> o.setPostIds(singleton(100L)));
userMapper.insert(user2);
userPostMapper.insert(new UserPostDO().setUserId(user2.getId()).setPostId(100L));
// 调用
List<AdminUserDO> result = userService.getUserListByPostIds(postIds);
// 断言
assertEquals(1, result.size());
assertEquals(user1, result.get(0));
}
|
Boolean validateProduct() {
try {
ResponseEntity<Boolean> productValidationResult = restTemplateBuilder
.build()
.postForEntity("http://localhost:30302/product/validate", "validating product",
Boolean.class);
LOGGER.info("Product validation result: {}", productValidationResult.getBody());
return productValidationResult.getBody();
} catch (ResourceAccessException | HttpClientErrorException e) {
LOGGER.error("Error communicating with product service: {}", e.getMessage());
return false;
}
}
|
@Test
void testValidateProduct() {
// Arrange
when(restTemplate.postForEntity(eq("http://localhost:30302/product/validate"), anyString(), eq(Boolean.class)))
.thenReturn(ResponseEntity.ok(true));
// Act
Boolean result = orderService.validateProduct();
// Assert
assertEquals(true, result);
}
|
public static String readFile(String path) throws IOException {
ClassPathResource classPathResource = new ClassPathResource(path);
if (classPathResource.exists() && classPathResource.isReadable()) {
try (InputStream inputStream = classPathResource.getInputStream()) {
return StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8);
}
}
return "";
}
|
@Test
public void testReadNotExistedFile() throws IOException {
String content = ResourceFileUtils.readFile("not_existed_test.txt");
assertThat(content).isEqualTo("");
}
|
public KsqlTarget target(final URI server) {
return target(server, Collections.emptyMap());
}
|
@Test
public void shouldOverrideAuthHeader() {
// Given:
setupExpectedResponse();
// When:
KsqlTarget target = ksqlClient.target(serverUri).authorizationHeader("other auth");
target.postKsqlRequest("some ksql", Collections.emptyMap(), Optional.of(123L));
// Then:
assertThat(server.getHeaders().get("Authorization"), is("other auth"));
}
|
@Override
public DescriptiveUrlBag toUrl(final Path file) {
if(DescriptiveUrl.EMPTY == file.attributes().getLink()) {
if(null == file.attributes().getFileId()) {
return DescriptiveUrlBag.empty();
}
final DescriptiveUrl share = toUrl(host, EueShareFeature.findShareForResource(shares,
file.attributes().getFileId()));
if(DescriptiveUrl.EMPTY == share) {
return DescriptiveUrlBag.empty();
}
return new DescriptiveUrlBag(Collections.singleton(share));
}
return new DescriptiveUrlBag(Collections.singleton(file.attributes().getLink()));
}
|
@Test
public void toUrl() {
assertEquals(DescriptiveUrl.EMPTY, new EueShareUrlProvider(new Host(new EueProtocol()), new UserSharesModel()).toUrl(
new Path("/f", EnumSet.of(Path.Type.file))).find(DescriptiveUrl.Type.signed));
}
|
public static int parseEightDigitsLittleEndian(final long bytes)
{
long val = bytes - 0x3030303030303030L;
val = (val * 10) + (val >> 8);
val = (((val & 0x000000FF000000FFL) * 0x000F424000000064L) +
(((val >> 16) & 0x000000FF000000FFL) * 0x0000271000000001L)) >> 32;
return (int)val;
}
|
@Test
void shouldParseEightDigitsFromAnAsciiEncodedNumberInLittleEndianByteOrder()
{
final int index = 3;
final UnsafeBuffer buffer = new UnsafeBuffer(new byte[16]);
for (int i = 10_000_000; i < 100_000_000; i += 111)
{
buffer.putIntAscii(index, i);
final long bytes = buffer.getLong(index, LITTLE_ENDIAN);
assertEquals(i, parseEightDigitsLittleEndian(bytes));
}
}
|
public static void executeWithRetry(RetryFunction function) throws Exception {
executeWithRetry(maxAttempts, minDelay, function);
}
|
@Test
public void retryFunctionThatRecoversAfterBiggerDelay() throws Exception {
startTimeMeasure = System.currentTimeMillis();
executeWithRetry(3, 2_000, IOITHelperTest::recoveringFunctionWithBiggerDelay);
assertEquals(1, listOfExceptionsThrown.size());
}
|
public static ParamType getSchemaFromType(final Type type) {
return getSchemaFromType(type, JAVA_TO_ARG_TYPE);
}
|
@Test
public void shouldGetGenericTriFunction() throws NoSuchMethodException {
// Given:
final Type genericType = getClass().getMethod("genericTriFunctionType").getGenericReturnType();
// When:
final ParamType returnType = UdfUtil.getSchemaFromType(genericType);
// Then:
assertThat(returnType, is(LambdaType.of(ImmutableList.of(GenericType.of("T"), GenericType.of("U"), GenericType.of("V")), GenericType.of("W"))));
}
|
@Override
public WindowStore<K, V> build() {
if (storeSupplier.retainDuplicates() && enableCaching) {
log.warn("Disabling caching for {} since store was configured to retain duplicates", storeSupplier.name());
enableCaching = false;
}
return new MeteredWindowStore<>(
maybeWrapCaching(maybeWrapLogging(storeSupplier.get())),
storeSupplier.windowSize(),
storeSupplier.metricsScope(),
time,
keySerde,
valueSerde);
}
|
@Test
public void shouldHaveCachingStoreWhenEnabled() {
setUp();
final WindowStore<String, String> store = builder.withCachingEnabled().build();
final StateStore wrapped = ((WrappedStateStore) store).wrapped();
assertThat(store, instanceOf(MeteredWindowStore.class));
assertThat(wrapped, instanceOf(CachingWindowStore.class));
}
|
@Override
public String toString() {
StringBuilder sb = new StringBuilder("PartitionRuntimeState [" + stamp + "]{" + System.lineSeparator());
for (PartitionReplica replica : allReplicas) {
sb.append(replica).append(System.lineSeparator());
}
sb.append(", completedMigrations=").append(completedMigrations);
sb.append('}');
return sb.toString();
}
|
@Test
public void toString_whenDeserializedTwice() throws UnknownHostException {
PartitionRuntimeState state = createPartitionState(0,
replica("127.0.0.1", 5701),
replica("127.0.0.2", 5702)
);
state = serializeAndDeserialize(state);
state = serializeAndDeserialize(state);
assertContains(state.toString(), "127.0.0.1");
assertContains(state.toString(), "127.0.0.2");
}
|
@Override
public boolean shouldFilter() {
RequestContext ctx = RequestContext.getCurrentContext();
return ctx.getThrowable() != null;
}
|
@Test
public void testShouldFilter() {
SentinelZuulErrorFilter sentinelZuulErrorFilter = new SentinelZuulErrorFilter();
RequestContext ctx = RequestContext.getCurrentContext();
ctx.setThrowable(new RuntimeException());
Assert.assertTrue(sentinelZuulErrorFilter.shouldFilter());
}
|
public boolean isScheduled() {
return (future != null) && !future.isDone();
}
|
@Test
public void isScheduled_doneFuture() {
pacer.future = DisabledFuture.INSTANCE;
assertThat(pacer.isScheduled()).isFalse();
}
|
public static void main(final String[] args) {
final var nums = new int[]{1, 2, 3, 4, 5};
//Before migration
final var oldSystem = new OldArithmetic(new OldSource());
oldSystem.sum(nums);
oldSystem.mul(nums);
//In process of migration
final var halfSystem = new HalfArithmetic(new HalfSource(), new OldSource());
halfSystem.sum(nums);
halfSystem.mul(nums);
halfSystem.ifHasZero(nums);
//After migration
final var newSystem = new NewArithmetic(new NewSource());
newSystem.sum(nums);
newSystem.mul(nums);
newSystem.ifHasZero(nums);
}
|
@Test
void shouldExecuteWithoutException() {
assertDoesNotThrow(() -> App.main(new String[]{}));
}
|
public void isNotEqualTo(@Nullable Object unexpected) {
standardIsNotEqualTo(unexpected);
}
|
@Test
public void isNotEqualToWithNulls() {
Object o = null;
assertThat(o).isNotEqualTo("a");
}
|
public String transform() throws ScanException {
StringBuilder stringBuilder = new StringBuilder();
compileNode(node, stringBuilder, new Stack<Node>());
return stringBuilder.toString();
}
|
@Test
public void nestedVariable() throws ScanException {
String input = "a${k${zero}}b";
Node node = makeNode(input);
NodeToStringTransformer nodeToStringTransformer = new NodeToStringTransformer(node, propertyContainer0);
Assertions.assertEquals("av0b", nodeToStringTransformer.transform());
}
|
public static <S> RemoteIterator<S> filteringRemoteIterator(
RemoteIterator<S> iterator,
FunctionRaisingIOE<? super S, Boolean> filter) {
return new FilteringRemoteIterator<>(iterator, filter);
}
|
@Test
public void testFiltering() throws Throwable {
CountdownRemoteIterator countdown = new CountdownRemoteIterator(100);
// only even numbers are passed through
RemoteIterator<Integer> it = filteringRemoteIterator(
countdown,
i -> (i % 2) == 0);
verifyInvoked(it, 50, c -> counter++);
assertCounterValue(50);
extractStatistics(it);
close(it);
countdown.assertCloseCount(1);
}
|
public static Builder newBuilder(PinotConfiguration pinotConfiguration) {
Builder builder = new Builder();
String maxConns = pinotConfiguration.getProperty(MAX_CONNS_CONFIG_NAME);
if (StringUtils.isNotEmpty(maxConns)) {
builder.withMaxConns(Integer.parseInt(maxConns));
}
String maxConnsPerRoute = pinotConfiguration.getProperty(MAX_CONNS_PER_ROUTE_CONFIG_NAME);
if (StringUtils.isNotEmpty(maxConnsPerRoute)) {
builder.withMaxConnsPerRoute(Integer.parseInt(maxConnsPerRoute));
}
boolean disableDefaultUserAgent = pinotConfiguration.getProperty(DISABLE_DEFAULT_USER_AGENT_CONFIG_NAME, false);
builder.withDisableDefaultUserAgent(disableDefaultUserAgent);
return builder;
}
|
@Test
public void testNewBuilder() {
// Ensure config values are picked up by the builder.
PinotConfiguration pinotConfiguration = new PinotConfiguration();
pinotConfiguration.setProperty(HttpClientConfig.MAX_CONNS_CONFIG_NAME, "123");
pinotConfiguration.setProperty(HttpClientConfig.MAX_CONNS_PER_ROUTE_CONFIG_NAME, "11");
pinotConfiguration.setProperty(HttpClientConfig.DISABLE_DEFAULT_USER_AGENT_CONFIG_NAME, "true");
HttpClientConfig httpClientConfig = HttpClientConfig.newBuilder(pinotConfiguration).build();
Assert.assertEquals(123, httpClientConfig.getMaxConnTotal());
Assert.assertEquals(11, httpClientConfig.getMaxConnPerRoute());
Assert.assertTrue(httpClientConfig.isDisableDefaultUserAgent());
// Ensure default builder uses negative values
HttpClientConfig defaultConfig = HttpClientConfig.newBuilder(new PinotConfiguration()).build();
Assert.assertTrue(defaultConfig.getMaxConnTotal() < 0, "default value should be < 0");
Assert.assertTrue(defaultConfig.getMaxConnPerRoute() < 0, "default value should be < 0");
Assert.assertFalse(defaultConfig.isDisableDefaultUserAgent(), "Default user agent should be enabled by default");
}
|
@POST
@Path("/{connector}/restart")
@Operation(summary = "Restart the specified connector")
public Response restartConnector(final @PathParam("connector") String connector,
final @Context HttpHeaders headers,
final @DefaultValue("false") @QueryParam("includeTasks") @Parameter(description = "Whether to also restart tasks") Boolean includeTasks,
final @DefaultValue("false") @QueryParam("onlyFailed") @Parameter(description = "Whether to only restart failed tasks/connectors")Boolean onlyFailed,
final @Parameter(hidden = true) @QueryParam("forward") Boolean forward) throws Throwable {
RestartRequest restartRequest = new RestartRequest(connector, onlyFailed, includeTasks);
String forwardingPath = "/connectors/" + connector + "/restart";
if (restartRequest.forceRestartConnectorOnly()) {
// For backward compatibility, just restart the connector instance and return OK with no body
FutureCallback<Void> cb = new FutureCallback<>();
herder.restartConnector(connector, cb);
requestHandler.completeOrForwardRequest(cb, forwardingPath, "POST", headers, null, forward);
return Response.noContent().build();
}
// In all other cases, submit the async restart request and return connector state
FutureCallback<ConnectorStateInfo> cb = new FutureCallback<>();
herder.restartConnectorAndTasks(restartRequest, cb);
Map<String, String> queryParameters = new HashMap<>();
queryParameters.put("includeTasks", includeTasks.toString());
queryParameters.put("onlyFailed", onlyFailed.toString());
ConnectorStateInfo stateInfo = requestHandler.completeOrForwardRequest(cb, forwardingPath, "POST", headers, queryParameters, null, new TypeReference<ConnectorStateInfo>() {
}, new IdentityTranslator<>(), forward);
return Response.accepted().entity(stateInfo).build();
}
|
@Test
public void testRestartConnectorOwnerRedirect() throws Throwable {
final ArgumentCaptor<Callback<Void>> cb = ArgumentCaptor.forClass(Callback.class);
String ownerUrl = "http://owner:8083";
expectAndCallbackException(cb, new NotAssignedException("not owner test", ownerUrl))
.when(herder).restartConnector(eq(CONNECTOR_NAME), cb.capture());
when(restClient.httpRequest(eq("http://owner:8083/connectors/" + CONNECTOR_NAME + "/restart?forward=false"), eq("POST"), isNull(), isNull(), any()))
.thenReturn(new RestClient.HttpResponse<>(202, new HashMap<>(), null));
Response response = connectorsResource.restartConnector(CONNECTOR_NAME, NULL_HEADERS, false, false, true);
assertEquals(Response.Status.NO_CONTENT.getStatusCode(), response.getStatus());
}
|
@RequiresApi(Build.VERSION_CODES.R)
@Override
public boolean onInlineSuggestionsResponse(@NonNull InlineSuggestionsResponse response) {
final List<InlineSuggestion> inlineSuggestions = response.getInlineSuggestions();
if (inlineSuggestions.size() > 0) {
mInlineSuggestionAction.onNewSuggestions(inlineSuggestions);
getInputViewContainer().addStripAction(mInlineSuggestionAction, true);
getInputViewContainer().setActionsStripVisibility(true);
}
return !inlineSuggestions.isEmpty();
}
|
@Test
public void testActionStripNotAddedIfEmptySuggestions() {
simulateOnStartInputFlow();
Assert.assertNull(
mAnySoftKeyboardUnderTest
.getInputViewContainer()
.findViewById(R.id.inline_suggestions_strip_root));
Assert.assertFalse(mAnySoftKeyboardUnderTest.onInlineSuggestionsResponse(mockResponse()));
Assert.assertNull(
mAnySoftKeyboardUnderTest
.getInputViewContainer()
.findViewById(R.id.inline_suggestions_strip_root));
}
|
public static List<FieldSchema> convert(Schema schema) {
return schema.columns().stream()
.map(col -> new FieldSchema(col.name(), convertToTypeString(col.type()), col.doc()))
.collect(Collectors.toList());
}
|
@Test
public void testSimpleSchemaConvertToHiveSchema() {
assertThat(HiveSchemaUtil.convert(SIMPLE_ICEBERG_SCHEMA)).isEqualTo(SIMPLE_HIVE_SCHEMA);
}
|
@Override
public GeometryState createSingleState()
{
return new SingleGeometryState();
}
|
@Test
public void testCreateSingleStatePresent()
{
GeometryState state = factory.createSingleState();
state.setGeometry(OGCGeometry.fromText("POINT (1 2)"), 0);
assertEquals(OGCGeometry.fromText("POINT (1 2)"), state.getGeometry());
assertTrue(state.getEstimatedSize() > 0, format("Estimated memory size was %d", state.getEstimatedSize()));
}
|
@Override
public String getVersionId(final Path file) throws BackgroundException {
if(StringUtils.isNotBlank(file.attributes().getVersionId())) {
if(log.isDebugEnabled()) {
log.debug(String.format("Return version %s from attributes for file %s", file.attributes().getVersionId(), file));
}
return file.attributes().getVersionId();
}
final String cached = super.getVersionId(file);
if(cached != null) {
if(log.isDebugEnabled()) {
log.debug(String.format("Return cached versionid %s for file %s", cached, file));
}
return cached;
}
try {
if(containerService.isContainer(file)) {
final B2BucketResponse info = session.getClient().listBucket(file.getName());
if(null == info) {
throw new NotfoundException(file.getAbsolute());
}
// Cache in file attributes
return this.cache(file, info.getBucketId());
}
// Files that have been hidden will not be returned
final B2ListFilesResponse response = session.getClient().listFileNames(
this.getVersionId(containerService.getContainer(file)), containerService.getKey(file), 1,
new DirectoryDelimiterPathContainerService().getKey(file.getParent()),
null);
// Find for exact filename match (.bzEmpty file for directories)
final Optional<B2FileInfoResponse> optional = response.getFiles().stream().filter(
info -> StringUtils.equals(containerService.getKey(file), info.getFileName())).findFirst();
if(optional.isPresent()) {
// Cache in file attributes
return this.cache(file, optional.get().getFileId());
}
if(file.isDirectory()) {
// Search for common prefix returned when no placeholder file was found
if(response.getFiles().stream().anyMatch(
info -> StringUtils.startsWith(info.getFileName(), new DirectoryDelimiterPathContainerService().getKey(file)))) {
if(log.isDebugEnabled()) {
log.debug(String.format("Common prefix found for %s but no placeholder file", file));
}
return null;
}
throw new NotfoundException(file.getAbsolute());
}
throw new NotfoundException(file.getAbsolute());
}
catch(B2ApiException e) {
throw new B2ExceptionMappingService(this).map(e);
}
catch(IOException e) {
throw new DefaultIOExceptionMappingService().map(e);
}
}
|
@Test
public void getFileIdDirectory() throws Exception {
final B2VersionIdProvider fileid = new B2VersionIdProvider(session);
final Path bucket = new B2DirectoryFeature(session, fileid).mkdir(new Path(new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory, Path.Type.volume)), new TransferStatus());
final Path folder = new B2DirectoryFeature(session, fileid).mkdir(new Path(bucket, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory)), new TransferStatus());
assertNotNull(fileid.getVersionId(folder));
new B2DeleteFeature(session, fileid).delete(Arrays.asList(folder, bucket), new DisabledLoginCallback(), new Delete.DisabledCallback());
}
|
@Nonnull
@Beta
public JobConfig addCustomClasspaths(@Nonnull String name, @Nonnull List<String> paths) {
throwIfLocked();
List<String> classpathItems = customClassPaths.computeIfAbsent(name, (k) -> new ArrayList<>());
classpathItems.addAll(paths);
return this;
}
|
@Test
public void addCustomClasspaths() {
JobConfig jobConfig = new JobConfig();
jobConfig.addCustomClasspaths("test", newArrayList("url1", "url2"));
jobConfig.addCustomClasspath("test", "url3");
assertThat(jobConfig.getCustomClassPaths()).containsValue(
newArrayList("url1", "url2", "url3")
);
}
|
public RuntimeOptionsBuilder parse(String... args) {
return parse(Arrays.asList(args));
}
|
@Test
void disables_default_summary_printer() {
RuntimeOptions options = parser
.parse("--no-summary", "--glue", "somewhere")
.addDefaultSummaryPrinterIfNotDisabled()
.build();
Plugins plugins = new Plugins(new PluginFactory(), options);
plugins.setEventBusOnEventListenerPlugins(new TimeServiceEventBus(Clock.systemUTC(), UUID::randomUUID));
assertAll(
() -> assertThat(plugins.getPlugins(),
not(hasItem(plugin("io.cucumber.core.plugin.DefaultSummaryPrinter")))));
}
|
public void validateAndMergeOutputParams(StepRuntimeSummary runtimeSummary) {
Optional<String> externalJobId = extractExternalJobId(runtimeSummary);
if (externalJobId.isPresent()) {
Optional<OutputData> outputDataOpt =
outputDataDao.getOutputDataForExternalJob(externalJobId.get(), ExternalJobType.TITUS);
outputDataOpt.ifPresent(
outputData -> {
ParamsMergeHelper.mergeOutputDataParams(
runtimeSummary.getParams(), outputData.getParams());
});
}
}
|
@Test
public void testMismatchedOutputParameterType() {
setupOutputDataDao();
runtimeSummary =
runtimeSummaryBuilder()
.artifacts(artifacts)
.params(
Collections.singletonMap(
"str_param",
LongParameter.builder()
.name("str_param")
.value(1L)
.evaluatedResult(1L)
.evaluatedTime(System.currentTimeMillis())
.build()))
.build();
AssertHelper.assertThrows(
"throws validation error if mismatched types",
MaestroValidationException.class,
"ParameterDefinition type mismatch name [str_param] from [STRING] != to [LONG]",
() -> outputDataManager.validateAndMergeOutputParams(runtimeSummary));
}
|
public void notifyAllocation(
AllocationID allocationId, FineGrainedTaskManagerSlot taskManagerSlot) {
Preconditions.checkNotNull(allocationId);
Preconditions.checkNotNull(taskManagerSlot);
switch (taskManagerSlot.getState()) {
case PENDING:
ResourceProfile newPendingResource =
pendingResource.merge(taskManagerSlot.getResourceProfile());
Preconditions.checkState(totalResource.allFieldsNoLessThan(newPendingResource));
pendingResource = newPendingResource;
break;
case ALLOCATED:
unusedResource = unusedResource.subtract(taskManagerSlot.getResourceProfile());
break;
default:
throw new IllegalStateException(
"The slot stat should not be FREE under fine-grained resource management.");
}
slots.put(allocationId, taskManagerSlot);
idleSince = Long.MAX_VALUE;
}
|
@Test
void testNotifyAllocationWithoutEnoughResource() {
final ResourceProfile totalResource = ResourceProfile.fromResources(1, 100);
final FineGrainedTaskManagerRegistration taskManager =
new FineGrainedTaskManagerRegistration(
TASK_EXECUTOR_CONNECTION, totalResource, totalResource);
final AllocationID allocationId = new AllocationID();
final JobID jobId = new JobID();
final FineGrainedTaskManagerSlot slot1 =
new FineGrainedTaskManagerSlot(
allocationId,
jobId,
ResourceProfile.fromResources(2, 100),
TASK_EXECUTOR_CONNECTION,
SlotState.PENDING);
final FineGrainedTaskManagerSlot slot2 =
new FineGrainedTaskManagerSlot(
allocationId,
jobId,
ResourceProfile.fromResources(2, 100),
TASK_EXECUTOR_CONNECTION,
SlotState.ALLOCATED);
final List<RuntimeException> exceptions = new ArrayList<>();
try {
taskManager.notifyAllocation(allocationId, slot1);
} catch (IllegalStateException e) {
exceptions.add(e);
}
try {
taskManager.notifyAllocation(allocationId, slot2);
} catch (IllegalArgumentException e) {
exceptions.add(e);
}
assertThat(exceptions).hasSize(2);
}
|
@Override
public void onProgressChanged(SeekBar seek, int value, boolean fromTouch) {
mValue = value + mMin;
if (mValue > mMax) mValue = mMax;
if (mValue < mMin) mValue = mMin;
if (shouldPersist()) persistInt(mValue);
callChangeListener(mValue);
if (mCurrentValue != null)
mCurrentValue.setText(String.format(Locale.ROOT, mValueTemplate, mValue));
}
|
@Test
public void testValueTemplateChanges() {
runTest(
() -> {
TextView templateView = mTestPrefFragment.getView().findViewById(R.id.pref_current_value);
Assert.assertNotNull(templateView);
Assert.assertEquals("23 milliseconds", templateView.getText().toString());
mTestSlide.onProgressChanged(
Mockito.mock(SeekBar.class), 15 /*this is zero-based*/, false);
Assert.assertEquals("27 milliseconds", templateView.getText().toString());
});
}
|
Modification modificationFromDescription(String output, ConsoleResult result) throws P4OutputParseException {
String[] parts = StringUtils.splitByWholeSeparator(output, SEPARATOR);
Pattern pattern = Pattern.compile(DESCRIBE_OUTPUT_PATTERN, Pattern.MULTILINE);
Matcher matcher = pattern.matcher(parts[0]);
if (matcher.find()) {
Modification modification = new Modification();
parseFistline(modification, matcher.group(1), result);
parseComment(matcher, modification);
parseAffectedFiles(parts, modification);
return modification;
}
throw new P4OutputParseException("Could not parse P4 description: " + output);
}
|
@Test
void shouldParseChangesWithLotsOfFilesWithoutError() throws IOException, P4OutputParseException {
final StringWriter writer = new StringWriter();
IOUtils.copy(new ClassPathResource("/BIG_P4_OUTPUT.txt").getInputStream(), writer, Charset.defaultCharset());
String output = writer.toString();
Modification modification = parser.modificationFromDescription(output, new ConsoleResult(0, new ArrayList<>(), new ArrayList<>(), new ArrayList<>(), new ArrayList<>()));
assertThat(modification.getModifiedFiles().size()).isEqualTo(1304);
assertThat(modification.getModifiedFiles().get(0).getFileName()).isEqualTo("Internal Projects/ABC/Customers3/ABC/RIP/SomeProject/data/main/config/lib/java/AdvJDBCColumnHandler.jar");
}
|
@Override
public void finished(boolean allStepsExecuted) {
if (postProjectAnalysisTasks.length == 0) {
return;
}
ProjectAnalysisImpl projectAnalysis = createProjectAnalysis(allStepsExecuted ? SUCCESS : FAILED);
for (PostProjectAnalysisTask postProjectAnalysisTask : postProjectAnalysisTasks) {
executeTask(projectAnalysis, postProjectAnalysisTask);
}
}
|
@Test
public void project_uuid_key_and_name_come_from_CeTask() {
underTest.finished(true);
verify(postProjectAnalysisTask).finished(taskContextCaptor.capture());
Project project = taskContextCaptor.getValue().getProjectAnalysis().getProject();
assertThat(project.getUuid()).isEqualTo(ceTask.getEntity().get().getUuid());
assertThat(project.getKey()).isEqualTo(ceTask.getEntity().get().getKey().get());
assertThat(project.getName()).isEqualTo(ceTask.getEntity().get().getName().get());
}
|
public MetricName metricName(String name, Map<String, String> tags) {
return explicitMetricName(this.pkg, this.simpleName, name, tags);
}
|
@Test
public void testConstructorWithPackageAndSimpleName() {
String packageName = "testPackage";
String simpleName = "testSimple";
KafkaMetricsGroup group = new KafkaMetricsGroup(packageName, simpleName);
MetricName metricName = group.metricName("metric-name", Collections.emptyMap());
assertEquals(packageName, metricName.getGroup());
assertEquals(simpleName, metricName.getType());
}
|
public TopicList getHasUnitSubUnUnitTopicList() {
TopicList topicList = new TopicList();
try {
this.lock.readLock().lockInterruptibly();
for (Entry<String, Map<String, QueueData>> topicEntry : this.topicQueueTable.entrySet()) {
String topic = topicEntry.getKey();
Map<String, QueueData> queueDatas = topicEntry.getValue();
if (queueDatas != null && queueDatas.size() > 0
&& !TopicSysFlag.hasUnitFlag(queueDatas.values().iterator().next().getTopicSysFlag())
&& TopicSysFlag.hasUnitSubFlag(queueDatas.values().iterator().next().getTopicSysFlag())) {
topicList.getTopicList().add(topic);
}
}
} catch (Exception e) {
log.error("getHasUnitSubUnUnitTopicList Exception", e);
} finally {
this.lock.readLock().unlock();
}
return topicList;
}
|
@Test
public void testGetHasUnitSubUnUnitTopicList() {
byte[] topicList = routeInfoManager.getHasUnitSubUnUnitTopicList().encode();
assertThat(topicList).isNotNull();
}
|
@Bean
@ConditionalOnMissingBean(EtcdDataDataChangedListener.class)
public DataChangedListener etcdDataChangedListener(final EtcdClient etcdClient) {
return new EtcdDataDataChangedListener(etcdClient);
}
|
@Test
public void testEtcdDataChangedListener() {
EtcdSyncConfiguration etcdListener = new EtcdSyncConfiguration();
EtcdClient client = mock(EtcdClient.class);
assertNotNull(etcdListener.etcdDataChangedListener(client));
}
|
@Override
public TableDataConsistencyCheckResult swapToObject(final YamlTableDataConsistencyCheckResult yamlConfig) {
if (null == yamlConfig) {
return null;
}
if (!Strings.isNullOrEmpty(yamlConfig.getIgnoredType())) {
return new TableDataConsistencyCheckResult(TableDataConsistencyCheckIgnoredType.valueOf(yamlConfig.getIgnoredType()));
}
return new TableDataConsistencyCheckResult(yamlConfig.isMatched());
}
|
@Test
void assertSwapToObjectWithEmptyYamlTableDataConsistencyCheckResultMatched() {
YamlTableDataConsistencyCheckResult yamlConfig = new YamlTableDataConsistencyCheckResult();
yamlConfig.setIgnoredType("");
TableDataConsistencyCheckResult result = yamlTableDataConsistencyCheckResultSwapper.swapToObject(yamlConfig);
assertNull(result.getIgnoredType());
assertFalse(result.isMatched());
}
|
public static PlanNodeStatsEstimate computeAntiJoin(PlanNodeStatsEstimate sourceStats, PlanNodeStatsEstimate filteringSourceStats, VariableReferenceExpression sourceJoinVariable, VariableReferenceExpression filteringSourceJoinVariable)
{
return compute(sourceStats, filteringSourceStats, sourceJoinVariable, filteringSourceJoinVariable,
(sourceJoinSymbolStats, filteringSourceJoinSymbolStats) ->
max(sourceJoinSymbolStats.getDistinctValuesCount() * MIN_ANTI_JOIN_FILTER_COEFFICIENT,
sourceJoinSymbolStats.getDistinctValuesCount() - filteringSourceJoinSymbolStats.getDistinctValuesCount()));
}
|
@Test
public void testAntiJoin()
{
// overlapping ranges
assertThat(computeAntiJoin(inputStatistics, inputStatistics, u, x))
.variableStats(u, stats -> stats
.lowValue(uStats.getLowValue())
.highValue(uStats.getHighValue())
.nullsFraction(0)
.distinctValuesCount(uStats.getDistinctValuesCount() - xStats.getDistinctValuesCount()))
.variableStats(x, stats -> stats.isEqualTo(xStats))
.variableStats(z, stats -> stats.isEqualTo(zStats))
.outputRowsCount(inputStatistics.getOutputRowCount() * uStats.getValuesFraction() * (1 - xStats.getDistinctValuesCount() / uStats.getDistinctValuesCount()));
// overlapping ranges, everything filtered out (but we leave 0.5 due to safety coefficient)
assertThat(computeAntiJoin(inputStatistics, inputStatistics, x, u))
.variableStats(x, stats -> stats
.lowValue(xStats.getLowValue())
.highValue(xStats.getHighValue())
.nullsFraction(0)
.distinctValuesCount(xStats.getDistinctValuesCount() * 0.5))
.variableStats(u, stats -> stats.isEqualTo(uStats))
.variableStats(z, stats -> stats.isEqualTo(zStats))
.outputRowsCount(inputStatistics.getOutputRowCount() * xStats.getValuesFraction() * 0.5);
// source stats are unknown
assertThat(computeAntiJoin(inputStatistics, inputStatistics, unknown, u))
.variableStats(unknown, stats -> stats
.nullsFraction(0)
.distinctValuesCountUnknown()
.unknownRange())
.variableStats(u, stats -> stats.isEqualTo(uStats))
.variableStats(z, stats -> stats.isEqualTo(zStats))
.outputRowsCountUnknown();
// filtering stats are unknown
assertThat(computeAntiJoin(inputStatistics, inputStatistics, x, unknown))
.variableStats(x, stats -> stats
.nullsFraction(0)
.lowValue(xStats.getLowValue())
.highValue(xStats.getHighValue())
.distinctValuesCountUnknown())
.variableStatsUnknown(unknown)
.variableStats(z, stats -> stats.isEqualTo(zStats))
.outputRowsCountUnknown();
// zero distinct values
assertThat(computeAntiJoin(inputStatistics, inputStatistics, emptyRange, emptyRange))
.outputRowsCount(0);
// fractional distinct values
assertThat(computeAntiJoin(inputStatistics, inputStatistics, fractionalNdv, fractionalNdv))
.outputRowsCount(500)
.variableStats(fractionalNdv, stats -> stats
.nullsFraction(0)
.distinctValuesCount(0.05));
}
|
public static void trackJPushAppOpenNotification(String extras,
String title,
String content,
String appPushChannel) {
if (!isTrackPushEnabled()) return;
SALog.i(TAG, String.format("trackJPushAppOpenNotification is called, title is %s, content is %s," +
" extras is %s, appPushChannel is %s, appPushServiceName is %s", title, content, extras, appPushChannel, "JPush"));
String sfData = getSFData(extras);
trackNotificationOpenedEvent(sfData, title, content, "JPush", appPushChannel);
}
|
@Test
public void trackJPushAppOpenNotification() {
PushAutoTrackHelper.trackJPushAppOpenNotification("", "mock_jpush", "mock_content", "JPush");
}
|
public int read(final MessageHandler handler)
{
return read(handler, Integer.MAX_VALUE);
}
|
@Test
void shouldCopeWithExceptionFromHandler()
{
final int msgLength = 16;
final int recordLength = HEADER_LENGTH + msgLength;
final int alignedRecordLength = align(recordLength, ALIGNMENT);
final long tail = alignedRecordLength * 2L;
final long head = 0L;
final int headIndex = (int)head;
when(buffer.getLong(HEAD_COUNTER_INDEX)).thenReturn(head);
when(buffer.getInt(typeOffset(headIndex))).thenReturn(MSG_TYPE_ID);
when(buffer.getIntVolatile(lengthOffset(headIndex))).thenReturn(recordLength);
when(buffer.getInt(typeOffset(headIndex + alignedRecordLength))).thenReturn(MSG_TYPE_ID);
when(buffer.getIntVolatile(lengthOffset(headIndex + alignedRecordLength))).thenReturn(recordLength);
final MutableInteger times = new MutableInteger();
final MessageHandler handler =
(msgTypeId, buffer, index, length) ->
{
if (times.incrementAndGet() == 2)
{
throw new RuntimeException();
}
};
try
{
ringBuffer.read(handler);
}
catch (final RuntimeException ignore)
{
assertThat(times.get(), is(2));
final InOrder inOrder = inOrder(buffer);
inOrder.verify(buffer, times(1)).setMemory(headIndex, alignedRecordLength * 2, (byte)0);
inOrder.verify(buffer, times(1)).putLongOrdered(HEAD_COUNTER_INDEX, tail);
return;
}
fail("Should have thrown exception");
}
|
public static String toString(InputStream input, String encoding) throws IOException {
if (input == null) {
return StringUtils.EMPTY;
}
return (null == encoding) ? toString(new InputStreamReader(input, Constants.ENCODE))
: toString(new InputStreamReader(input, encoding));
}
|
@Test
void testToStringWithNull() throws IOException {
assertEquals("", IoUtils.toString(null, "UTF-8"));
}
|
@Override
public Boolean match(final List<ConditionData> conditionDataList, final ServerWebExchange exchange) {
return conditionDataList
.stream()
.allMatch(condition -> PredicateJudgeFactory.judge(condition, buildRealData(condition, exchange)));
}
|
@Test
public void testMatch() {
assertTrue(matchStrategy.match(conditionDataList, exchange));
}
|
@PostConstruct
public void init() {
if (!environment.getAgentStatusEnabled()) {
LOG.info("Agent status HTTP API server has been disabled.");
return;
}
InetSocketAddress address = new InetSocketAddress(environment.getAgentStatusHostname(), environment.getAgentStatusPort());
try {
server = HttpServer.create(address, SERVER_SOCKET_BACKLOG);
setupRoutes(server);
server.start();
LOG.info("Agent status HTTP API server running on http://{}:{}.", server.getAddress().getHostName(), server.getAddress().getPort());
} catch (Exception e) {
LOG.warn("Could not start agent status HTTP API server on host {}, port {}.", address.getHostName(), address.getPort(), e);
}
}
|
@Test
void initShouldNotBlowUpIfServerDoesNotStart() {
try (MockedStatic<HttpServer> mockedStaticHttpServer = mockStatic(HttpServer.class)) {
setupAgentStatusParameters();
var serverSocket = new InetSocketAddress(hostName, port);
var spiedHttpServer = spy(HttpServer.class);
doThrow(new RuntimeException("Server had a problem starting up!")).when(spiedHttpServer).start();
mockedStaticHttpServer.when(() -> HttpServer.create(eq(serverSocket), anyInt())).thenReturn(spiedHttpServer);
assertThatNoException().isThrownBy(() -> agentStatusHttpd.init());
}
}
|
@Override
public void post(final Transfer.Type type, final Map<TransferItem, TransferStatus> files, final ConnectionCallback callback) throws BackgroundException {
final Map<TransferItem, TransferStatus> encrypted = new HashMap<>(files.size());
for(Map.Entry<TransferItem, TransferStatus> entry : files.entrySet()) {
final TransferStatus status = entry.getValue();
encrypted.put(new TransferItem(cryptomator.encrypt(session, entry.getKey().remote), entry.getKey().local), status);
}
delegate.post(type, encrypted, callback);
}
|
@Test
public void testPost() throws Exception {
final Path vault = new Path("/vault", EnumSet.of(Path.Type.directory));
final NullSession session = new NullSession(new Host(new TestProtocol())) {
@Override
@SuppressWarnings("unchecked")
public <T> T _getFeature(final Class<T> type) {
if(type == Directory.class) {
return (T) new Directory() {
@Override
public Path mkdir(final Path folder, final TransferStatus status) {
return folder;
}
@Override
public Directory withWriter(final Write writer) {
return this;
}
};
}
return super._getFeature(type);
}
};
final CryptoVault cryptomator = new CryptoVault(vault);
cryptomator.create(session, null, new VaultCredentials("test"));
final CryptoBulkFeature<Map<TransferItem, TransferStatus>> bulk = new CryptoBulkFeature<Map<TransferItem, TransferStatus>>(session, new Bulk<Map<TransferItem, TransferStatus>>() {
@Override
public Map<TransferItem, TransferStatus> pre(final Transfer.Type type, final Map<TransferItem, TransferStatus> files, final ConnectionCallback callback) {
return files;
}
@Override
public void post(final Transfer.Type type, final Map<TransferItem, TransferStatus> files, final ConnectionCallback callback) {
//
}
@Override
public Bulk<Map<TransferItem, TransferStatus>> withDelete(final Delete delete) {
return this;
}
}, new Delete() {
@Override
public void delete(final Map<Path, TransferStatus> files, final PasswordCallback prompt, final Callback callback) {
throw new UnsupportedOperationException();
}
@Override
public boolean isRecursive() {
throw new UnsupportedOperationException();
}
}, cryptomator);
final HashMap<TransferItem, TransferStatus> files = new HashMap<>();
final Path directory = new Path("/vault/directory", EnumSet.of(Path.Type.directory));
files.put(new TransferItem(directory, new Local("/tmp/vault/directory")), new TransferStatus().exists(false));
files.put(new TransferItem(new Path(directory, "file1", EnumSet.of(Path.Type.file)), new Local("/tmp/vault/directory/file1")), new TransferStatus().exists(false));
files.put(new TransferItem(new Path(directory, "file2", EnumSet.of(Path.Type.file)), new Local("/tmp/vault/directory/file2")), new TransferStatus().exists(false));
bulk.post(Transfer.Type.upload, files, new DisabledConnectionCallback());
}
|
@VisibleForTesting
boolean hasMenuEntries(MenuEntry[] menuEntries)
{
for (MenuEntry menuEntry : menuEntries)
{
MenuAction action = menuEntry.getType();
switch (action)
{
case CANCEL:
case WALK:
break;
case EXAMINE_OBJECT:
case EXAMINE_NPC:
case EXAMINE_ITEM_GROUND:
case EXAMINE_ITEM:
case CC_OP_LOW_PRIORITY:
if (config.rightClickExamine())
{
return true;
}
break;
case GAME_OBJECT_FIRST_OPTION:
case GAME_OBJECT_SECOND_OPTION:
case GAME_OBJECT_THIRD_OPTION:
case GAME_OBJECT_FOURTH_OPTION:
case GAME_OBJECT_FIFTH_OPTION:
case NPC_FIRST_OPTION:
case NPC_SECOND_OPTION:
case NPC_THIRD_OPTION:
case NPC_FOURTH_OPTION:
case NPC_FIFTH_OPTION:
case GROUND_ITEM_FIRST_OPTION:
case GROUND_ITEM_SECOND_OPTION:
case GROUND_ITEM_THIRD_OPTION:
case GROUND_ITEM_FOURTH_OPTION:
case GROUND_ITEM_FIFTH_OPTION:
case PLAYER_FIRST_OPTION:
case PLAYER_SECOND_OPTION:
case PLAYER_THIRD_OPTION:
case PLAYER_FOURTH_OPTION:
case PLAYER_FIFTH_OPTION:
case PLAYER_SIXTH_OPTION:
case PLAYER_SEVENTH_OPTION:
case PLAYER_EIGHTH_OPTION:
if (config.rightClickObjects())
{
return true;
}
break;
default:
return true;
}
}
return false;
}
|
@Test
public void testHasMenuEntries()
{
/*
right click examine? right click object? move camera
has object op Y Y N
Y N N
N Y N
N N Y
has examine op Y Y N
Y N N
N Y Y
N N Y
*/
test(true, true, true, true, false);
test(true, true, true, false, false);
test(true, true, false, true, false);
test(true, true, false, false, true);
test(false, true, true, true, false);
test(false, true, true, false, false);
test(false, true, false, true, true);
test(false, true, false, false, true);
}
|
@Override
public List<Intent> compile(PointToPointIntent intent, List<Intent> installable) {
log.trace("compiling {} {}", intent, installable);
ConnectPoint ingressPoint = intent.filteredIngressPoint().connectPoint();
ConnectPoint egressPoint = intent.filteredEgressPoint().connectPoint();
//TODO: handle protected path case with suggested path!!
//Idea: use suggested path as primary and another path from path service as protection
if (intent.suggestedPath() != null && intent.suggestedPath().size() > 0) {
Path path = new DefaultPath(PID, intent.suggestedPath(), new ScalarWeight(1));
//Check intent constraints against suggested path and suggested path availability
if (checkPath(path, intent.constraints()) && pathAvailable(intent)) {
allocateIntentBandwidth(intent, path);
return asList(createLinkCollectionIntent(ImmutableSet.copyOf(intent.suggestedPath()),
DEFAULT_COST, intent));
}
}
if (ingressPoint.deviceId().equals(egressPoint.deviceId())) {
return createZeroHopLinkCollectionIntent(intent);
}
// proceed with no protected paths
if (!ProtectionConstraint.requireProtectedPath(intent)) {
return createUnprotectedLinkCollectionIntent(intent);
}
try {
// attempt to compute and implement backup path
return createProtectedIntent(ingressPoint, egressPoint, intent, installable);
} catch (PathNotFoundException e) {
log.warn("Could not find disjoint Path for {}", intent);
// no disjoint path extant -- maximum one path exists between devices
return createSinglePathIntent(ingressPoint, egressPoint, intent, installable);
}
}
|
@Test
public void testForwardPathCompilation() {
PointToPointIntent intent = makeIntent(new ConnectPoint(DID_1, PORT_1),
new ConnectPoint(DID_8, PORT_1));
String[] hops = {S1, S2, S3, S4, S5, S6, S7, S8};
PointToPointIntentCompiler compiler = makeCompiler(hops);
List<Intent> result = compiler.compile(intent, null);
assertThat(result, is(Matchers.notNullValue()));
assertThat(result, hasSize(1));
Intent forwardResultIntent = result.get(0);
assertThat(forwardResultIntent instanceof LinkCollectionIntent, is(true));
if (forwardResultIntent instanceof LinkCollectionIntent) {
LinkCollectionIntent forwardIntent = (LinkCollectionIntent) forwardResultIntent;
FilteredConnectPoint ingressPoint = new FilteredConnectPoint(new ConnectPoint(DID_1, PORT_1));
FilteredConnectPoint egressPoint = new FilteredConnectPoint(new ConnectPoint(DID_8, PORT_1));
// 7 links for the hops, plus one default lnk on ingress and egress
assertThat(forwardIntent.links(), hasSize(hops.length - 1));
assertThat(forwardIntent.links(), linksHasPath(S1, S2));
assertThat(forwardIntent.links(), linksHasPath(S2, S3));
assertThat(forwardIntent.links(), linksHasPath(S3, S4));
assertThat(forwardIntent.links(), linksHasPath(S4, S5));
assertThat(forwardIntent.links(), linksHasPath(S5, S6));
assertThat(forwardIntent.links(), linksHasPath(S6, S7));
assertThat(forwardIntent.links(), linksHasPath(S7, S8));
assertThat(forwardIntent.filteredIngressPoints(), is(ImmutableSet.of(ingressPoint)));
assertThat(forwardIntent.filteredEgressPoints(), is(ImmutableSet.of(egressPoint)));
}
assertThat("key is inherited", forwardResultIntent.key(), is(intent.key()));
}
|
public synchronized AlertResult send(String content) {
SmsResponse smsResponse;
if (supplierConfigLoader.isPresent() && supplierConfigLoader.get().getTemplateId() != null) {
String templateId = supplierConfigLoader.get().getTemplateId();
smsResponse = smsSendFactory.massTexting(phoneNumbers, templateId, buildPlatFormVariableOfContent(content));
} else {
throw new RuntimeException("sms templateId is null");
}
return validateSendResult(smsResponse);
}
|
@Ignore
@Test
public void testSendMsg() {
SmsAlert weChatAlert = new SmsAlert();
AlertConfig alertConfig = new AlertConfig();
alertConfig.setType(SmsConstants.TYPE);
alertConfig.setParam(SMS_CONFIG);
weChatAlert.setConfig(alertConfig);
AlertResult alertResult =
weChatAlert.send(AlertBaseConstant.ALERT_TEMPLATE_TITLE, AlertBaseConstant.ALERT_TEMPLATE_MSG);
Assert.assertEquals(true, alertResult.getSuccess());
}
|
public static String encodeChecked(Integer version, byte[] data) {
return encode(addChecksum(version, data));
}
|
@Test
public void encodeCheckedTest() {
String a = "hello world";
String encode = Base58.encodeChecked(0, a.getBytes());
assertEquals(1 + "3vQB7B6MrGQZaxCuFg4oh", encode);
// 无版本位
encode = Base58.encodeChecked(null, a.getBytes());
assertEquals("3vQB7B6MrGQZaxCuFg4oh", encode);
}
|
static void fireChannelRead(ChannelHandlerContext ctx, List<Object> msgs, int numElements) {
if (msgs instanceof CodecOutputList) {
fireChannelRead(ctx, (CodecOutputList) msgs, numElements);
} else {
for (int i = 0; i < numElements; i++) {
ctx.fireChannelRead(msgs.get(i));
}
}
}
|
@Test
public void testRemoveWhileInCallDecode() {
final Object upgradeMessage = new Object();
final ByteToMessageDecoder decoder = new ByteToMessageDecoder() {
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
assertEquals('a', in.readByte());
out.add(upgradeMessage);
}
};
EmbeddedChannel channel = new EmbeddedChannel(decoder, new ChannelInboundHandlerAdapter() {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (msg == upgradeMessage) {
ctx.pipeline().remove(decoder);
return;
}
ctx.fireChannelRead(msg);
}
});
ByteBuf buf = Unpooled.wrappedBuffer(new byte[] { 'a', 'b', 'c' });
assertTrue(channel.writeInbound(buf.copy()));
ByteBuf b = channel.readInbound();
assertEquals(b, buf.skipBytes(1));
assertFalse(channel.finish());
buf.release();
b.release();
}
|
public static ResourceId relativize(ResourceId base, ResourceId child) {
checkArgument(child.nodeKeys().size() >= base.nodeKeys().size(),
"%s path must be deeper than base prefix %s", child, base);
@SuppressWarnings("rawtypes")
Iterator<NodeKey> bIt = base.nodeKeys().iterator();
@SuppressWarnings("rawtypes")
Iterator<NodeKey> cIt = child.nodeKeys().iterator();
while (bIt.hasNext()) {
NodeKey<?> b = bIt.next();
NodeKey<?> c = cIt.next();
checkArgument(Objects.equals(b, c),
"%s is not a prefix of %s.\n" +
"b:%s != c:%s",
base, child,
b, c);
}
return ResourceId.builder().append(child.nodeKeys().subList(base.nodeKeys().size(),
child.nodeKeys().size())).build();
}
|
@Test
public void testRelativizeEmpty() {
ResourceId relDevices = ResourceIds.relativize(DEVICES, DEVICES);
// equivalent of . in file path, expressed as ResourceId with empty
assertTrue(relDevices.nodeKeys().isEmpty());
}
|
public Optional<Violation> validate(IndexSetConfig newConfig) {
// Don't validate prefix conflicts in case of an update
if (Strings.isNullOrEmpty(newConfig.id())) {
final Violation prefixViolation = validatePrefix(newConfig);
if (prefixViolation != null) {
return Optional.of(prefixViolation);
}
}
final Violation fieldMappingViolation = validateMappingChangesAreLegal(newConfig);
if (fieldMappingViolation != null) {
return Optional.of(fieldMappingViolation);
}
Violation refreshIntervalViolation = validateSimpleIndexSetConfig(newConfig);
if (refreshIntervalViolation != null){
return Optional.of(refreshIntervalViolation);
}
return Optional.empty();
}
|
@Test
public void validate() throws Exception {
final IndexSet indexSet = mock(IndexSet.class);
when(indexSetRegistry.iterator()).thenReturn(Collections.singleton(indexSet).iterator());
when(indexSet.getIndexPrefix()).thenReturn("foo");
IndexSetConfig validConfig = testIndexSetConfig();
final Optional<IndexSetValidator.Violation> violation = validator.validate(validConfig);
assertThat(violation).isNotPresent();
}
|
public static String unescape(String escaped) {
boolean escaping = false;
StringBuilder newString = new StringBuilder();
for (char c : escaped.toCharArray()) {
if (!escaping) {
if (c == ESCAPE_CHAR) {
escaping = true;
} else {
newString.append(c);
}
} else {
if (c == 'n') {
newString.append('\n');
} else if (c == 'r') {
newString.append('\r');
} else {
newString.append(c);
}
escaping = false;
}
}
return newString.toString();
}
|
@Test
public void testWithLineBreaks() {
assertEquals("Hello\\nWorld!", StringUtil.unescape("Hello\\\\nWorld!"));
assertEquals("Hello\nWorld!", StringUtil.unescape("Hello\\nWorld!"));
assertEquals("Hello\\\nWorld!", StringUtil.unescape("Hello\\\\\\nWorld!"));
assertEquals("\rHello\\\nWorld!", StringUtil.unescape("\\rHello\\\\\\nWorld!"));
}
|
@Override
public Optional<PersistentQueryMetadata> getPersistentQuery(final QueryId queryId) {
return Optional.ofNullable(persistentQueries.get(queryId));
}
|
@Test
public void shouldCallListenerOnError() {
// Given:
final QueryMetadata.Listener queryListener = givenCreateGetListener(registry, "foo");
final QueryMetadata query = registry.getPersistentQuery(new QueryId("foo")).get();
final QueryError error = new QueryError(123L, "error", Type.USER);
// When:
queryListener.onError(query, error);
// Then:
verify(listener1).onError(query, error);
verify(listener2).onError(query, error);
}
|
@Override
public String getMethod() {
return PATH;
}
|
@Test
public void testSetMyCommandsWithAllSet() {
SetMyCommands setMyCommands = SetMyCommands
.builder()
.command(BotCommand.builder().command("test").description("Test description").build())
.languageCode("en")
.scope(BotCommandScopeDefault.builder().build())
.build();
assertEquals("setMyCommands", setMyCommands.getMethod());
assertDoesNotThrow(setMyCommands::validate);
}
|
@Udf
public <T> List<T> except(
@UdfParameter(description = "Array of values") final List<T> left,
@UdfParameter(description = "Array of exceptions") final List<T> right) {
if (left == null || right == null) {
return null;
}
final Set<T> distinctRightValues = new HashSet<>(right);
final Set<T> distinctLeftValues = new LinkedHashSet<>(left);
return distinctLeftValues
.stream()
.filter(e -> !distinctRightValues.contains(e))
.collect(Collectors.toList());
}
|
@Test
public void shouldExceptNulls() {
final List<String> input1 = Arrays.asList("foo", null, "foo", "bar");
final List<String> input2 = Arrays.asList(null, "foo");
final List<String> result = udf.except(input1, input2);
assertThat(result, contains("bar"));
}
|
synchronized ActivateWorkResult activateWorkForKey(ExecutableWork executableWork) {
ShardedKey shardedKey = executableWork.work().getShardedKey();
Deque<ExecutableWork> workQueue = activeWork.getOrDefault(shardedKey, new ArrayDeque<>());
// This key does not have any work queued up on it. Create one, insert Work, and mark the work
// to be executed.
if (!activeWork.containsKey(shardedKey) || workQueue.isEmpty()) {
workQueue.addLast(executableWork);
activeWork.put(shardedKey, workQueue);
incrementActiveWorkBudget(executableWork.work());
return ActivateWorkResult.EXECUTE;
}
// Check to see if we have this work token queued.
Iterator<ExecutableWork> workIterator = workQueue.iterator();
while (workIterator.hasNext()) {
ExecutableWork queuedWork = workIterator.next();
if (queuedWork.id().equals(executableWork.id())) {
return ActivateWorkResult.DUPLICATE;
}
if (queuedWork.id().cacheToken() == executableWork.id().cacheToken()) {
if (executableWork.id().workToken() > queuedWork.id().workToken()) {
// Check to see if the queuedWork is active. We only want to remove it if it is NOT
// currently active.
if (!queuedWork.equals(workQueue.peek())) {
workIterator.remove();
decrementActiveWorkBudget(queuedWork.work());
}
// Continue here to possibly remove more non-active stale work that is queued.
} else {
return ActivateWorkResult.STALE;
}
}
}
// Queue the work for later processing.
workQueue.addLast(executableWork);
incrementActiveWorkBudget(executableWork.work());
return ActivateWorkResult.QUEUED;
}
|
@Test
public void
testActivateWorkForKey_matchingCacheTokens_newWorkTokenGreater_queuedWorkIsActive_QUEUED() {
long cacheToken = 1L;
long newWorkToken = 10L;
long queuedWorkToken = newWorkToken / 2;
ShardedKey shardedKey = shardedKey("someKey", 1L);
ExecutableWork queuedWork = createWork(createWorkItem(queuedWorkToken, cacheToken, shardedKey));
ExecutableWork newWork = createWork(createWorkItem(newWorkToken, cacheToken, shardedKey));
activeWorkState.activateWorkForKey(queuedWork);
ActivateWorkResult activateWorkResult = activeWorkState.activateWorkForKey(newWork);
// newWork should be queued and queuedWork should not be removed since it is currently active.
assertEquals(ActivateWorkResult.QUEUED, activateWorkResult);
assertTrue(readOnlyActiveWork.get(shardedKey).contains(newWork));
assertEquals(queuedWork, readOnlyActiveWork.get(shardedKey).peek());
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.