focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public void parse(InputStream stream, ContentHandler handler, Metadata metadata, ParseContext context) throws IOException, SAXException, TikaException { // Get the mime4j configuration, or use a default one MimeConfig config = new MimeConfig.Builder().setMaxLineLen(...
@Test public void testLongHeader() throws Exception { StringBuilder inputBuilder = new StringBuilder(); for (int i = 0; i < 2000; ++i) { inputBuilder.append( //len > 50 "really really really really really really long name "); } String name = inputBuild...
public T send() throws IOException { return web3jService.send(this, responseType); }
@Test public void testEthSubmitWork() throws Exception { web3j.ethSubmitWork( "0x0000000000000001", "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef", "0xD1FE5700000000000000000000000000D1FE570000000000000000000000000...
@Override public long size() throws IOException { return delegate.size(); }
@Test public void testSize() throws IOException { assertEquals(delegate.size(), channelUnderTest.size()); }
static String consumerGroupJoinKey(String groupId, String memberId) { return "join-" + groupId + "-" + memberId; }
@Test public void testConsumerGroupMemberUsingClassicProtocolFencedWhenJoinTimeout() { String groupId = "group-id"; String memberId = Uuid.randomUuid().toString(); int rebalanceTimeout = 500; List<ConsumerGroupMemberMetadataValue.ClassicProtocol> protocols = Collections.singletonLis...
@Override @CacheEvict(cacheNames = RedisKeyConstants.NOTIFY_TEMPLATE, allEntries = true) // allEntries 清空所有缓存,因为可能修改到 code 字段,不好清理 public void updateNotifyTemplate(NotifyTemplateSaveReqVO updateReqVO) { // 校验存在 validateNotifyTemplateExists(updateReqVO.getId()); // 校验站内信编码是否重复...
@Test public void testUpdateNotifyTemplate_success() { // mock 数据 NotifyTemplateDO dbNotifyTemplate = randomPojo(NotifyTemplateDO.class); notifyTemplateMapper.insert(dbNotifyTemplate);// @Sql: 先插入出一条存在的数据 // 准备参数 NotifyTemplateSaveReqVO reqVO = randomPojo(NotifyTemplateSaveRe...
Map<String, File> scanExistingUsers() throws IOException { Map<String, File> users = new HashMap<>(); File[] userDirectories = listUserDirectories(); if (userDirectories != null) { for (File directory : userDirectories) { String userId = idStrategy.idFromFilename(dire...
@Test public void scanExistingUsersNoUsersDirectory() throws IOException { UserIdMigrator migrator = createUserIdMigrator(); Map<String, File> userMappings = migrator.scanExistingUsers(); assertThat(userMappings.keySet(), empty()); }
@Override public int hashCode() { return Objects.hash(targetImage, imageDigest, imageId, tags, imagePushed); }
@Test public void testEquality_differentTargetImage() { JibContainer container1 = new JibContainer(targetImage1, digest1, digest2, tags1, true); JibContainer container2 = new JibContainer(targetImage2, digest1, digest2, tags1, true); Assert.assertNotEquals(container1, container2); Assert.assertNotEqu...
public String getGetterName(String propertyName, JType type, JsonNode node) { propertyName = getPropertyNameForAccessor(propertyName, node); String prefix = type.equals(type.owner()._ref(boolean.class)) ? "is" : "get"; String getterName; if (propertyName.length() > 1 && Character.isUpp...
@Test public void testGetterNamedCorrectly() { assertThat(nameHelper.getGetterName("foo", new JCodeModel().BOOLEAN, NODE), is("isFoo")); assertThat(nameHelper.getGetterName("foo", new JCodeModel().INT, NODE), is("getFoo")); assertThat(nameHelper.getGetterName("oAuth2State", new JCodeModel()....
@Override public ExportResult<MediaContainerResource> export(UUID jobId, AD authData, Optional<ExportInformation> exportInfo) throws Exception { ExportResult<PhotosContainerResource> per = exportPhotos(jobId, authData, exportInfo); if (per.getThrowable().isPresent()) { return new ExportResult<>(pe...
@Test public void shouldMergePhotoAndVideoResults() throws Exception { MediaContainerResource mcr = new MediaContainerResource(albums, photos, videos); ExportResult<MediaContainerResource> exp = new ExportResult<>(ResultType.END, mcr); Optional<ExportInformation> ei = Optional.of(new ExportInformation(nu...
public boolean isValid(String value) { if (value == null) { return false; } URI uri; // ensure value is a valid URI try { uri = new URI(value); } catch (URISyntaxException e) { return false; } // OK, perfom additional validatio...
@Test public void testValidator380() { UrlValidator validator = new UrlValidator(); assertTrue(validator.isValid("http://www.apache.org:80/path")); assertTrue(validator.isValid("http://www.apache.org:8/path")); assertTrue(validator.isValid("http://www.apache.org:/path")); }
@Override public ConfigOperateResult insertOrUpdateTagCas(final ConfigInfo configInfo, final String tag, final String srcIp, final String srcUser) { if (findConfigInfo4TagState(configInfo.getDataId(), configInfo.getGroup(), configInfo.getTenant(), tag) == null) { return addConfigInfo...
@Test void testInsertOrUpdateTagCasOfAdd() { String dataId = "dataId111222"; String group = "group"; String tenant = "tenant"; String appName = "appname1234"; String content = "c12345"; ConfigInfo configInfo = new ConfigInfo(dataId, group, tenant, appName, co...
public static List<Annotation> scanMethod(Method method) { return AnnotationScanner.TYPE_HIERARCHY.getAnnotationsIfSupport(method); }
@Test public void scanMethodTest() { // TargetClass -> TargetSuperClass // -> TargetSuperInterface final Method method = ReflectUtil.getMethod(TargetClass.class, "testMethod"); assertNotNull(method); final List<Annotation> annotations = AnnotationUtil.scanMethod(method); assertEquals(3, annotat...
public static OptExpression bind(Pattern pattern, GroupExpression groupExpression) { Binder binder = new Binder(pattern, groupExpression); return binder.next(); }
@Test public void testBinder3() { OptExpression expr = OptExpression.create(new MockOperator(OperatorType.LOGICAL_OLAP_SCAN), new OptExpression(new MockOperator(OperatorType.LOGICAL_JOIN)), new OptExpression(new MockOperator(OperatorType.LOGICAL_OLAP_SCAN))); Pattern...
@CanIgnoreReturnValue public final Ordered containsExactly(@Nullable Object @Nullable ... varargs) { List<@Nullable Object> expected = (varargs == null) ? newArrayList((@Nullable Object) null) : asList(varargs); return containsExactlyElementsIn( expected, varargs != null && varargs.length == 1...
@Test public void iterableContainsExactlyWithDuplicates() { assertThat(asList(1, 2, 2, 2, 3)).containsExactly(1, 2, 2, 2, 3); }
public void setBaseResource(Resource baseResource) { handler.setBaseResource(baseResource); }
@Test void setsBaseResource(@TempDir Path tempDir) throws Exception { final Resource testResource = Resource.newResource(tempDir.resolve("dir").toUri()); environment.setBaseResource(testResource); assertThat(handler.getBaseResource()).isEqualTo(testResource); }
@Override public void transform(Message message, DataType fromType, DataType toType) { if (message.getHeaders().containsKey(Ddb2Constants.ITEM) || message.getHeaders().containsKey(Ddb2Constants.KEY)) { return; } JsonNode jsonBody = getBodyAsJsonNode(message); ...
@Test @SuppressWarnings("unchecked") void shouldMapPutItemHeaders() throws Exception { Exchange exchange = new DefaultExchange(camelContext); exchange.getMessage().setBody(Json.mapper().readTree(itemJson)); exchange.setProperty("operation", Ddb2Operations.PutItem.name()); transf...
@Description("count number of set bits in 2's complement representation") @ScalarFunction @SqlType(StandardTypes.BIGINT) public static long bitCount(@SqlType(StandardTypes.BIGINT) long num, @SqlType(StandardTypes.BIGINT) long bits) { if (bits == MAX_BITS) { return Long.bitCount(num);...
@Test public void testBitCount() { assertFunction("bit_count(0, 64)", BIGINT, 0L); assertFunction("bit_count(7, 64)", BIGINT, 3L); assertFunction("bit_count(24, 64)", BIGINT, 2L); assertFunction("bit_count(-8, 64)", BIGINT, 61L); assertFunction("bit_count(" + Integer.MAX_...
protected void removeAllModels() { int numModelsRemoved = models.size(); pauseModelListNotifications(); models.clear(); resumeModelListNotifications(); notifyItemRangeRemoved(0, numModelsRemoved); }
@Test public void testRemoveAllModels() { for (int i = 0; i < 10; i++) { TestModel model = new TestModel(); testAdapter.addModels(model); } testAdapter.removeAllModels(); verify(observer).onItemRangeRemoved(0, 10); assertEquals(0, testAdapter.models.size()); checkDifferState(); ...
Record deserialize(Object data) { return (Record) fieldDeserializer.value(data); }
@Test public void testListDeserialize() { Schema schema = new Schema(optional(1, "list_type", Types.ListType.ofOptional(2, Types.LongType.get()))); StructObjectInspector inspector = ObjectInspectorFactory.getStandardStructObjectInspector( Arrays.asList("list_type"), Ar...
public static SchemaAndValue parseString(String value) { if (value == null) { return NULL_SCHEMA_AND_VALUE; } if (value.isEmpty()) { return new SchemaAndValue(Schema.STRING_SCHEMA, value); } ValueParser parser = new ValueParser(new Parser(value)); ...
@Test public void shouldParseDateStringAsDateInArray() throws Exception { String dateStr = "2019-08-23"; String arrayStr = "[" + dateStr + "]"; SchemaAndValue result = Values.parseString(arrayStr); assertEquals(Type.ARRAY, result.schema().type()); Schema elementSchema = resul...
public void addIndexes(int maxIndex, int[] dictionaryIndexes, int indexCount) { if (indexCount == 0 && indexRetainedBytes > 0) { // Ignore empty segment, since there are other segments present. return; } checkState(maxIndex >= lastMaxIndex, "LastMax is greater than the...
@Test public void testByteIndexes() { int[] dictionaryIndexes = createIndexArray(Byte.MAX_VALUE + 1, MAX_DICTIONARY_INDEX); for (int length : ImmutableList.of(0, 10, dictionaryIndexes.length)) { DictionaryRowGroupBuilder rowGroupBuilder = new DictionaryRowGroupBuilder(); ...
@Override public Flux<BooleanResponse<RenameCommand>> rename(Publisher<RenameCommand> commands) { return execute(commands, command -> { Assert.notNull(command.getKey(), "Key must not be null!"); Assert.notNull(command.getNewKey(), "New name must not be null!"); byte[] k...
@Test public void testRename() { testInClusterReactive(connection -> { connection.stringCommands().set(originalKey, value).block(); if (hasTtl) { connection.keyCommands().expire(originalKey, Duration.ofSeconds(1000)).block(); } Integer origin...
public static void trace(Logger logger, String msg) { if (logger == null) { return; } if (logger.isTraceEnabled()) { logger.trace(msg); } }
@Test void testTrace() { Logger logger = Mockito.mock(Logger.class); when(logger.isTraceEnabled()).thenReturn(true); LogHelper.trace(logger, "trace"); verify(logger).trace("trace"); Throwable t = new RuntimeException(); LogHelper.trace(logger, t); verify(logge...
@Override public Collection<LocalDataQueryResultRow> getRows(final ShowComputeNodeInfoStatement sqlStatement, final ContextManager contextManager) { ComputeNodeInstance instance = contextManager.getComputeNodeInstanceContext().getInstance(); InstanceMetaData instanceMetaData = instance.getMetaData()...
@Test void assertExecute() { ShowComputeNodeInfoExecutor executor = new ShowComputeNodeInfoExecutor(); ContextManager contextManager = mock(ContextManager.class); ComputeNodeInstanceContext computeNodeInstanceContext = createInstanceContext(); when(contextManager.getComputeNodeInstan...
@Override public List<BlockWorkerInfo> getPreferredWorkers(WorkerClusterView workerClusterView, String fileId, int count) throws ResourceExhaustedException { if (workerClusterView.size() < count) { throw new ResourceExhaustedException(String.format( "Not enough workers in the cluster %d work...
@Test public void workerAddrUpdateWithIdUnchanged() throws Exception { KetamaHashPolicy policy = new KetamaHashPolicy(mConf); List<WorkerInfo> workers = new ArrayList<>(); workers.add(new WorkerInfo().setIdentity(WorkerIdentityTestUtils.ofLegacyId(1L)) .setAddress(new WorkerNetAddress().setHost("h...
protected void declareConstraintNotIn(final String patternType, final List<Object> values) { String constraints = getInNotInConstraint(values); builder.not().pattern(patternType).constraint(constraints); }
@Test void declareConstraintNotIn() { List<Object> values = Arrays.asList("3", "8.5"); String patternType = "INPUT2"; KiePMMLDescrLhsFactory.factory(lhsBuilder).declareConstraintNotIn(patternType, values); final List<BaseDescr> descrs = lhsBuilder.getDescr().getDescrs(); asse...
static <T> int[] getValidIndexes(T[] inputs) { int[] validIndexes = new int[inputs.length]; int idx = 0; for (int i = 0; i < inputs.length; i++) { if (inputs[i] != null) { validIndexes[idx++] = i; } } return Arrays.copyOf(validIndexes, idx); }
@Test public void testGetValidIndexes() { byte[][] inputs = new byte[numInputs][]; inputs[0] = new byte[chunkSize]; inputs[1] = new byte[chunkSize]; inputs[7] = new byte[chunkSize]; inputs[8] = new byte[chunkSize]; int[] validIndexes = CoderUtil.getValidIndexes(inputs); assertEquals(4, v...
@Override public FileStatus[] listStatus(Path path) throws IOException { LOG.debug("listStatus({})", path); if (mStatistics != null) { mStatistics.incrementReadOps(1); } AlluxioURI uri = getAlluxioPath(path); List<URIStatus> statuses; try { ListStatusPOptions listStatusPOptions =...
@Test public void listStatus() throws Exception { FileInfo fileInfo1 = new FileInfo() .setLastModificationTimeMs(111L) .setLastAccessTimeMs(123L) .setFolder(false) .setOwner("user1") .setGroup("group1") .setMode(00755); FileInfo fileInfo2 = new FileInfo() ...
public List<PermissionInfo> getPermissions(String role) { List<PermissionInfo> permissionInfoList = permissionInfoMap.get(role); if (!authConfigs.isCachingEnabled() || permissionInfoList == null) { Page<PermissionInfo> permissionInfoPage = getPermissionsFromDatabase(role, DEFAULT_PAGE_NO, ...
@Test void getPermissions() { boolean cachingEnabled = authConfigs.isCachingEnabled(); assertFalse(cachingEnabled); List<PermissionInfo> permissions = nacosRoleService.getPermissions("role-admin"); assertEquals(permissions, Collections.emptyList()); }
public static <T> T[] clone(T[] array) { if (array == null) { return null; } return array.clone(); }
@Test public void cloneTest() { Integer[] b = {1, 2, 3}; Integer[] cloneB = ArrayUtil.clone(b); assertArrayEquals(b, cloneB); int[] a = {1, 2, 3}; int[] clone = ArrayUtil.clone(a); assertArrayEquals(a, clone); }
@Override public Map<String, String> generationCodes(Long tableId) { // 校验是否已经存在 CodegenTableDO table = codegenTableMapper.selectById(tableId); if (table == null) { throw exception(CODEGEN_TABLE_NOT_EXISTS); } List<CodegenColumnDO> columns = codegenColumnMapper.se...
@Test public void testGenerationCodes_one_success() { // mock 数据(CodegenTableDO) CodegenTableDO table = randomPojo(CodegenTableDO.class, o -> o.setScene(CodegenSceneEnum.ADMIN.getScene()) .setTemplateType(CodegenTemplateTypeEnum.ONE.getType())); codege...
public static <T> T convert(Class<T> type, Object value) throws ConvertException { return convert((Type) type, value); }
@Test public void localDateTimeToLocalDateTest() { final LocalDateTime localDateTime = LocalDateTime.now(); final LocalDate convert = Convert.convert(LocalDate.class, localDateTime); assertEquals(localDateTime.toLocalDate(), convert); }
protected boolean needFiltering(Exchange exchange) { // exchange property takes precedence over data format property return exchange == null ? filterNonXmlChars : exchange.getProperty(Exchange.FILTER_NON_XML_CHARS, filterNonXmlChars, Boolean.class); }
@Test public void testNeedFilteringTruePropagates() { Exchange exchange = new DefaultExchange(camelContext); exchange.setProperty(Exchange.FILTER_NON_XML_CHARS, Boolean.TRUE); assertTrue(jaxbDataFormat.needFiltering(exchange)); }
public NetworkId networkId() { return networkId; }
@Test public void testEquality() { DefaultVirtualDevice device1 = new DefaultVirtualDevice(NetworkId.networkId(0), DID1); DefaultVirtualDevice device2 = new DefaultVirtualDevice(NetworkId.networkId(0), DID2); ConnectPoint cpA = new ConnectPoint(device1.id(), ...
boolean empty() { return empty; }
@Test public void testEmpty() { LogReplayTracker tracker = new LogReplayTracker.Builder().build(); assertTrue(tracker.empty()); tracker.replay(new NoOpRecord()); assertFalse(tracker.empty()); }
@Override public long getPeriod() { return config.getLong(PERIOD_IN_MILISECONDS_PROPERTY).orElse(10_000L); }
@Test public void getPeriod_returnNumberFromConfig() { config.put("sonar.server.monitoring.other.period", "100000"); long delay = underTest.getPeriod(); assertThat(delay).isEqualTo(100_000L); }
public static FEEL_1_1Parser parse(FEELEventListenersManager eventsManager, String source, Map<String, Type> inputVariableTypes, Map<String, Object> inputVariables, Collection<FEELFunction> additionalFunctions, List<FEELProfile> profiles, FEELTypeRegistry typeRegistry) { CharStream input = CharStreams.fromStrin...
@Test void functionInvocationEmptyParams() { String inputExpression = "my.test.Function()"; BaseNode functionBase = parse( inputExpression ); assertThat( functionBase).isInstanceOf(FunctionInvocationNode.class); assertThat( functionBase.getText()).isEqualTo(inputExpression); ...
@Override public JobDetails postProcess(JobDetails jobDetails) { if (isNotNullOrEmpty(substringBetween(jobDetails.getClassName(), "$$", "$$"))) { return new JobDetails( substringBefore(jobDetails.getClassName(), "$$"), jobDetails.getStaticFieldName(), ...
@Test void postProcessWithSpringCGLibReturnsUpdatedJobDetails() { // GIVEN final JobDetails jobDetails = defaultJobDetails().withClassName(TestService.class.getName() + "$$EnhancerBySpringCGLIB$$6aee664d").build(); // WHEN final JobDetails result = cgLibPostProcessor.postProcess(job...
public static <V> Read<V> read() { return new AutoValue_SparkReceiverIO_Read.Builder<V>().build(); }
@Test public void testReadObjectCreationFailsIfStartPollTimeoutSecIsNull() { assertThrows( IllegalArgumentException.class, () -> SparkReceiverIO.<String>read().withStartPollTimeoutSec(null)); }
@Override public <T extends State> T state(StateNamespace namespace, StateTag<T> address) { return workItemState.get(namespace, address, StateContexts.nullContext()); }
@Test public void testWatermarkAddBeforeReadEarliest() throws Exception { StateTag<WatermarkHoldState> addr = StateTags.watermarkStateInternal("watermark", TimestampCombiner.EARLIEST); WatermarkHoldState bag = underTest.state(NAMESPACE, addr); SettableFuture<Instant> future = SettableFuture.creat...
public static AssertionResult getResult(SMIMEAssertionTestElement testElement, SampleResult response, String name) { checkForBouncycastle(); AssertionResult res = new AssertionResult(name); try { MimeMessage msg; final int msgPos = testElement.getSpecificMessagePositionAs...
@Test public void testSignerSerial() { SMIMEAssertionTestElement testElement = new SMIMEAssertionTestElement(); testElement.setSignerCheckConstraints(true); testElement.setSignerSerial("0xc8c46f8fbf9ebea4"); AssertionResult result = SMIMEAssertion.getResult(testElement, parent, ...
public static Config fromMap(Map<String, ?> map) { return fromMap("Map@" + System.identityHashCode(map), map); }
@Test void testFromMap() { var config = MapConfigFactory.fromMap(Map.of( "field1", "value1", "field2", 2, "field3", List.of(1, "2"), "field4", Map.of( "f1", 1 ) )); assertThat(config.get(ConfigValuePath.root().child...
@Override public void handleExecutionsTermination(Collection<ExecutionState> terminatedExecutionStates) { final Set<ExecutionState> notFinishedExecutionStates = checkNotNull(terminatedExecutionStates).stream() .filter(state -> state != ExecutionState.FINISHED) ...
@Test void testSavepointCreationFailureWithFailingExecutions() { // no global fail-over is expected to be triggered by the stop-with-savepoint despite the // execution failure assertSavepointCreationFailure( testInstance -> testInstance.handleExecution...
@VisibleForTesting void removeQueues(String args, SchedConfUpdateInfo updateInfo) { if (args == null) { return; } List<String> queuesToRemove = Arrays.asList(args.split(";")); updateInfo.setRemoveQueueInfo(new ArrayList<>(queuesToRemove)); }
@Test(timeout = 10000) public void testRemoveQueues() { SchedConfUpdateInfo schedUpdateInfo = new SchedConfUpdateInfo(); cli.removeQueues("root.a;root.b;root.c.c1", schedUpdateInfo); List<String> removeInfo = schedUpdateInfo.getRemoveQueueInfo(); assertEquals(3, removeInfo.size()); assertEquals("r...
@Override public void merge(ColumnStatisticsObj aggregateColStats, ColumnStatisticsObj newColStats) { LOG.debug("Merging statistics: [aggregateColStats:{}, newColStats: {}]", aggregateColStats, newColStats); LongColumnStatsDataInspector aggregateData = longInspectorFromStats(aggregateColStats); LongColum...
@Test public void testMergeNonNullWithNullValues() { ColumnStatisticsObj aggrObj = createColumnStatisticsObj(new ColStatsBuilder<>(long.class) .low(1L) .high(3L) .numNulls(4) .numDVs(2) .hll(1, 3, 3) .kll(1, 3, 3) .build()); ColumnStatisticsObj newObj =...
@Override public void reload(AppSettings settings) throws IOException { if (ClusterSettings.isClusterEnabled(settings)) { throw new IllegalStateException("Restart is not possible with cluster mode"); } AppSettings reloaded = settingsLoader.load(); ensureUnchangedConfiguration(settings.getProps()...
@Test public void throw_ISE_if_cluster_is_enabled() throws IOException { AppSettings settings = new TestAppSettings(ImmutableMap.of(CLUSTER_ENABLED.getKey(), "true")); assertThatThrownBy(() -> { underTest.reload(settings); verifyNoInteractions(logging); verifyNoInteractions(state); v...
public static void writeAndFlushWithClosePromise(ChannelOutboundInvoker ctx, ByteBuf msg) { ctx.writeAndFlush(msg).addListener(ChannelFutureListener.CLOSE); }
@Test public void testWriteAndFlushWithClosePromise() { final ChannelOutboundInvoker ctx = mock(ChannelOutboundInvoker.class); final ChannelPromise promise = mock(ChannelPromise.class); final byte[] data = "test".getBytes(StandardCharsets.UTF_8); final ByteBuf byteBuf = Unpooled.wra...
public static SubqueryTableSegment bind(final SubqueryTableSegment segment, final SQLStatementBinderContext binderContext, final Map<String, TableSegmentBinderContext> tableBinderContexts, final Map<String, TableSegmentBinderContext> outerTableBinderContexts) { fillPi...
@Test void assertBindWithSubqueryTableAlias() { MySQLSelectStatement selectStatement = mock(MySQLSelectStatement.class); when(selectStatement.getDatabaseType()).thenReturn(databaseType); when(selectStatement.getFrom()).thenReturn(Optional.of(new SimpleTableSegment(new TableNameSegment(0, 0, ...
public static AwsCredentialsProvider create(boolean isCloud, @Nullable String stsRegion, @Nullable String accessKey, @Nullable String secretKey, ...
@Test public void testAutomaticAuthIsFailingInCloudWithInvalidSecretKey() { assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> AWSAuthFactory.create(true, null, "key", null, null)) .withMessageContaining("Secret key"); }
@Override public Path move(final Path source, final Path renamed, final TransferStatus status, final Delete.Callback callback, final ConnectionCallback connectionCallback) throws BackgroundException { Path target; if(source.attributes().getCustom().containsKey(KEY_DELETE_MARKER)) { // De...
@Test public void testMoveVersioned() throws Exception { final Path container = new Path("versioning-test-eu-central-1-cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume)); Path test = new Path(container, new AsciiRandomStringService().random(), EnumSet.of(Path.Type.file)); final S...
static PublicationParams getPublicationParams( final ChannelUri channelUri, final MediaDriver.Context ctx, final DriverConductor driverConductor, final boolean isIpc) { final PublicationParams params = new PublicationParams(ctx, isIpc); params.getEntityTag(channelUri...
@Test void hasInvalidMaxRetransmits() { final ChannelUri uri = ChannelUri.parse("aeron:udp?endpoint=localhost:1010|" + CommonContext.MAX_RESEND_PARAM_NAME + "=notanumber"); final IllegalArgumentException exception = assertThrows( IllegalArgumentException.class, ...
void decode(int streamId, ByteBuf in, Http2Headers headers, boolean validateHeaders) throws Http2Exception { Http2HeadersSink sink = new Http2HeadersSink( streamId, headers, maxHeaderListSize, validateHeaders); // Check for dynamic table size updates, which must occur at the beginning: ...
@Test public void testIncompleteIndex() throws Http2Exception { byte[] compressed = StringUtil.decodeHexDump("FFF0"); final ByteBuf in = Unpooled.wrappedBuffer(compressed); try { assertEquals(2, in.readableBytes()); assertThrows(Http2Exception.class, new Executable() ...
@Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Tuple2<?, ?> tuple2 = (Tuple2<?, ?>) o; return Objects.equals(f0, tuple2.f0) && Objects.equals(f1, tuple2.f1); }
@Test public void testEquals() { assertEquals(Tuple2.of(1, "a"), Tuple2.of(1, "a")); assertEquals(Tuple2.of(1, "a").hashCode(), Tuple2.of(1, "a").hashCode()); }
Set<SourceName> analyzeExpression( final Expression expression, final String clauseType ) { final Validator extractor = new Validator(clauseType); extractor.process(expression, null); return extractor.referencedSources; }
@Test public void shouldThrowOnNoSources() { // Given: final Expression expression = new UnqualifiedColumnReferenceExp( ColumnName.of("just-name") ); when(sourceSchemas.sourcesWithField(any(), any())) .thenReturn(ImmutableSet.of()); // When: final Exception e = assertThrows( ...
@Override public void releaseAll() throws Exception { Collection<String> children = getAllHandles(); Exception exception = null; for (String child : children) { try { release(child); } catch (Exception e) { exception = ExceptionUtils....
@Test void testReleaseAll() throws Exception { final TestingLongStateHandleHelper longStateStorage = new TestingLongStateHandleHelper(); ZooKeeperStateHandleStore<TestingLongStateHandleHelper.LongStateHandle> zkStore = new ZooKeeperStateHandleStore<>(getZooKeeperClient(), longStateS...
public FEELFnResult<List<BigDecimal>> invoke(@ParameterName( "list" ) List list, @ParameterName( "match" ) Object match) { if ( list == null ) { return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "list", "cannot be null")); } final List<BigDecimal> result = new A...
@Test void invokeBigDecimal() { FunctionTestUtil.assertResult(indexOfFunction.invoke(Arrays.asList("test", null, 12), BigDecimal.valueOf(12)) , Collections.emptyList()); FunctionTestUtil.assertResult( indexOfFunction.invoke(Arrays.asList("test", null, BigDecimal.value...
@Override public boolean alterOffsets(Map<String, String> config, Map<Map<String, ?>, Map<String, ?>> offsets) { for (Map.Entry<Map<String, ?>, Map<String, ?>> offsetEntry : offsets.entrySet()) { Map<String, ?> sourceOffset = offsetEntry.getValue(); if (sourceOffset == null) { ...
@Test public void testAlterOffsetsIncorrectPartitionKey() { MirrorHeartbeatConnector connector = new MirrorHeartbeatConnector(); assertThrows(ConnectException.class, () -> connector.alterOffsets(null, Collections.singletonMap( Collections.singletonMap("unused_partition_key", "unused_...
public static String limitSizeTo1KB(String desc) { if (desc.length() < 1024) { return desc; } else { return desc.substring(0, 1024); } }
@Test void limitSizeTo1KB() { String a = "a"; for (int i = 0; i < 11; i++) { a += a; } Assertions.assertEquals(1024, TriRpcStatus.limitSizeTo1KB(a).length()); Assertions.assertEquals(1, TriRpcStatus.limitSizeTo1KB("a").length()); }
public static Map<String, String> getStreamConfigMap(TableConfig tableConfig) { String tableNameWithType = tableConfig.getTableName(); Preconditions.checkState(tableConfig.getTableType() == TableType.REALTIME, "Cannot fetch streamConfigs for OFFLINE table: %s", tableNameWithType); Map<String, String...
@Test public void testGetStreamConfigMap() { TableConfig tableConfig = new TableConfigBuilder(TableType.OFFLINE).setTableName("myTable").build(); try { IngestionConfigUtils.getStreamConfigMap(tableConfig); Assert.fail("Should fail for OFFLINE table"); } catch (IllegalStateException e) { ...
public static Bech32Data decode(final String str) throws AddressFormatException { boolean lower = false, upper = false; if (str.length() < 8) throw new AddressFormatException.InvalidDataLength("Input too short: " + str.length()); if (str.length() > 90) throw new AddressFo...
@Test(expected = AddressFormatException.InvalidCharacter.class) public void decode_invalidCharacter_upperLowerMix() { Bech32.decode("A12UeL5X"); }
String buildCustomMessage(EventNotificationContext ctx, SlackEventNotificationConfig config, String template) throws PermanentEventNotificationException { final List<MessageSummary> backlog = getMessageBacklog(ctx, config); Map<String, Object> model = getCustomMessageModel(ctx, config.type(), backlog, c...
@Test public void testCustomMessage() throws PermanentEventNotificationException { SlackEventNotificationConfig slackConfig = SlackEventNotificationConfig.builder() .backlogSize(5) .build(); String message = slackEventNotification.buildCustomMessage(eventNotification...
public Optional<DispatchEvent> build(final String databaseName, final DataChangedEvent event) { for (RuleNodePathProvider each : ShardingSphereServiceLoader.getServiceInstances(RuleNodePathProvider.class)) { Optional<DispatchEvent> result = build(each.getRuleNodePath(), databaseName, event); ...
@Test void assertBuildWithoutRuleNodePathProvider() { when(ShardingSphereServiceLoader.getServiceInstances(RuleNodePathProvider.class)).thenReturn(Collections.emptyList()); assertFalse(new RuleConfigurationEventBuilder().build("foo_db", new DataChangedEvent("k", "v", Type.IGNORED)).isPresent()); ...
@Override protected EnumDeclaration create(CompilationUnit compilationUnit) { EnumDeclaration lambdaClass = super.create(compilationUnit); boolean hasDroolsParameter = lambdaParameters.stream().anyMatch(this::isDroolsParameter); if (hasDroolsParameter) { bitMaskVariables.forEach...
@Test public void createConsequenceWithMultipleFactUpdate() { ArrayList<String> personFields = new ArrayList<>(); personFields.add("\"name\""); MaterializedLambda.BitMaskVariable bitMaskPerson = new MaterializedLambda.BitMaskVariableWithFields("DomainClassesMetadataB45236F6195B110E0FA3A5447B...
public void upgrade() { viewService.streamAll().forEach(view -> { final Optional<User> user = view.owner().map(userService::load); if (user.isPresent() && !user.get().isLocalAdmin()) { final GRNType grnType = ViewDTO.Type.DASHBOARD.equals(view.type()) ? GRNTypes.DASHBOARD...
@Test @DisplayName("don't migrate non-existing owner") void dontmigrateNonExistingOwner() { final GRN testuserGRN = GRNTypes.USER.toGRN("olduser"); final GRN dashboard = GRNTypes.DASHBOARD.toGRN("54e3deadbeefdeadbeef0003"); when(userService.load(anyString())).thenReturn(null); m...
public static ShenyuAdminResult error(final String msg) { return error(CommonErrorCode.ERROR, msg); }
@Test public void testErrorWithMsg() { final ShenyuAdminResult result = ShenyuAdminResult.error(0, "msg"); assertEquals(0, result.getCode().intValue()); assertEquals("msg", result.getMessage()); assertNull(result.getData()); assertEquals(3390718, result.hashCode()); a...
public List<ShardingCondition> createShardingConditions(final InsertStatementContext sqlStatementContext, final List<Object> params) { List<ShardingCondition> result = null == sqlStatementContext.getInsertSelectContext() ? createShardingConditionsWithInsertValues(sqlStatementContext, params) ...
@Test void assertCreateShardingConditionsSelectStatementWithGeneratedKeyContext() { when(insertStatementContext.getGeneratedKeyContext()).thenReturn(Optional.of(mock(GeneratedKeyContext.class))); when(insertStatementContext.getInsertSelectContext()).thenReturn(mock(InsertSelectContext.class)); ...
public static <K, V> V getOrPutSynchronized(ConcurrentMap<K, V> map, K key, final Object mutex, ConstructorFunction<K, V> func) { if (mutex == null) { throw new NullPointerException(); } V value = map.get(key); if (value == null...
@SuppressWarnings("ConstantConditions") @Test(expected = NullPointerException.class) public void testGetOrPutSynchronized_whenMutexIsNull_thenThrowException() { ConcurrencyUtil.getOrPutSynchronized(map, 5, (Object) null, constructorFunction); }
public static DeleteGroupsResponseData.DeletableGroupResultCollection getErrorResultCollection( List<String> groupIds, Errors error ) { DeleteGroupsResponseData.DeletableGroupResultCollection resultCollection = new DeleteGroupsResponseData.DeletableGroupResultCollection(); ...
@Test public void testGetErrorResultCollection() { String groupId1 = "group-id-1"; String groupId2 = "group-id-2"; DeleteGroupsRequestData data = new DeleteGroupsRequestData() .setGroupsNames(Arrays.asList(groupId1, groupId2)); DeleteGroupsResponseData.DeletableGroupResul...
public static boolean canDrop( FilterPredicate pred, List<ColumnChunkMetaData> columns, DictionaryPageReadStore dictionaries) { Objects.requireNonNull(pred, "pred cannnot be null"); Objects.requireNonNull(columns, "columns cannnot be null"); return pred.accept(new DictionaryFilter(columns, dictionarie...
@Test public void testInFixed() throws Exception { BinaryColumn b = binaryColumn("fixed_field"); // Only V2 supports dictionary encoding for FIXED_LEN_BYTE_ARRAY values if (version == PARQUET_2_0) { Set<Binary> set1 = new HashSet<>(); set1.add(toBinary("-2", 17)); set1.add(toBinary("-22...
public long put(final K key, final V value, final long timestamp) { if (timestampedStore != null) { timestampedStore.put(key, ValueAndTimestamp.make(value, timestamp)); return PUT_RETURN_CODE_IS_LATEST; } if (versionedStore != null) { return versionedStore.put...
@Test public void shouldPutToVersionedStore() { givenWrapperWithVersionedStore(); when(versionedStore.put(KEY, VALUE_AND_TIMESTAMP.value(), VALUE_AND_TIMESTAMP.timestamp())).thenReturn(12L); final long putReturnCode = wrapper.put(KEY, VALUE_AND_TIMESTAMP.value(), VALUE_AND_TIMESTAMP.timesta...
public AstNode rewrite(final AstNode node, final C context) { return rewriter.process(node, context); }
@Test public void shouldRewriteInsertInto() { // Given: final InsertInto ii = new InsertInto(location, sourceName, query, insertIntoProperties); when(mockRewriter.apply(query, context)).thenReturn(rewrittenQuery); // When: final AstNode rewritten = rewriter.rewrite(ii, context); // Then: ...
@Override public ClusterInfo clusterGetClusterInfo() { RFuture<Map<String, String>> f = executorService.readAsync((String)null, StringCodec.INSTANCE, RedisCommands.CLUSTER_INFO); Map<String, String> entries = syncFuture(f); Properties props = new Properties(); for (Entry<String, Str...
@Test public void testClusterGetClusterInfo() { ClusterInfo info = connection.clusterGetClusterInfo(); assertThat(info.getSlotsFail()).isEqualTo(0); assertThat(info.getSlotsOk()).isEqualTo(MasterSlaveConnectionManager.MAX_SLOT); assertThat(info.getSlotsAssigned()).isEqualTo(MasterSla...
public void shutdown() { DefaultMetricsSystem.shutdown(); }
@Test public void testResourceCheck() throws Exception { HdfsConfiguration conf = new HdfsConfiguration(); File basedir = new File(MiniDFSCluster.getBaseDirectory(), GenericTestUtils.getMethodName()); MiniDFSCluster tmpCluster = new MiniDFSCluster.Builder(conf, basedir) .numDataNodes(0) ...
public List<MetricsKey> getMetricsKeys() { return metricsKeys; }
@Override @Test public void testSerialize() throws JsonProcessingException { ClientConfigMetricRequest clientMetrics = new ClientConfigMetricRequest(); clientMetrics.putAllHeader(HEADERS); clientMetrics.getMetricsKeys() .add(ClientConfigMetricRequest.MetricsKey.build(CACH...
@Operation(summary = "list", description = "List components") @GetMapping public ResponseEntity<List<ComponentVO>> list(@PathVariable Long clusterId) { return ResponseEntity.success(componentService.list(clusterId)); }
@Test void listReturnsEmptyForNoComponents() { Long clusterId = 1L; when(componentService.list(clusterId)).thenReturn(List.of()); ResponseEntity<List<ComponentVO>> response = componentController.list(clusterId); assertTrue(response.isSuccess()); assertTrue(response.getData(...
public LinkedHashMap<String, String> getKeyPropertyList(ObjectName mbeanName) { LinkedHashMap<String, String> keyProperties = keyPropertiesPerBean.get(mbeanName); if (keyProperties == null) { keyProperties = new LinkedHashMap<>(); String properties = mbeanName.getKeyPropertyListS...
@Test public void testQuotedObjectNameWithQuote() throws Throwable { JmxMBeanPropertyCache testCache = new JmxMBeanPropertyCache(); LinkedHashMap<String, String> parameterList = testCache.getKeyPropertyList( new ObjectName("com.organisation:name=\"value\\\"mor...
static void populateMissingOutputFieldDataType(final Model model, final List<DataField> dataFields) { if (model.getOutput() != null && model.getOutput().getOutputFields() != null) { populateMissingOutputFieldDataType(model.getOutput().getOutputFields(), ...
@Test void populateMissingOutputFieldDataType() { Random random = new Random(); List<String> fieldNames = IntStream.range(0, 6) .mapToObj(i -> RandomStringUtils.random(6, true, false)) .collect(Collectors.toList()); List<DataField> dataFields = fieldNames.stre...
public synchronized void addLocation(URI location, TaskId remoteSourceTaskId) { requireNonNull(location, "location is null"); // Ignore new locations after close // NOTE: this MUST happen before checking no more locations is checked if (closed.get()) { return; } ...
@Test(timeOut = 10000) public void testAddLocation() throws Exception { DataSize bufferCapacity = new DataSize(32, MEGABYTE); DataSize maxResponseSize = new DataSize(10, MEGABYTE); MockExchangeRequestProcessor processor = new MockExchangeRequestProcessor(maxResponseSize); ...
public static UnifiedDiff parseUnifiedDiff(InputStream stream) throws IOException, UnifiedDiffParserException { UnifiedDiffReader parser = new UnifiedDiffReader(new BufferedReader(new InputStreamReader(stream))); return parser.parse(); }
@Test public void testParseIssue107_2() throws IOException { UnifiedDiff diff = UnifiedDiffReader.parseUnifiedDiff( UnifiedDiffReaderTest.class.getResourceAsStream("problem_diff_issue107.diff")); assertThat(diff.getFiles().size()).isEqualTo(2); UnifiedDiffFile file1 = diff....
public static void ensureTopic( final String name, final KsqlConfig ksqlConfig, final KafkaTopicClient topicClient ) { if (topicClient.isTopicExists(name)) { validateTopicConfig(name, ksqlConfig, topicClient); return; } final short replicationFactor = ksqlConfig .get...
@Test public void shouldCreateInternalTopicIfItDoesNotExist() { // When: KsqlInternalTopicUtils.ensureTopic(TOPIC_NAME, ksqlConfig, topicClient); // Then: verify(topicClient).createTopic(TOPIC_NAME, 1, NREPLICAS, commandTopicConfig); }
@Override public boolean enableSendingOldValues(final boolean forceMaterialization) { if (queryableName != null) { sendOldValues = true; return true; } if (parent.enableSendingOldValues(forceMaterialization)) { sendOldValues = true; } retu...
@Test public void shouldEnableSendOldValuesWhenNotMaterializedAlreadyButForcedToMaterialize() { final StreamsBuilder builder = new StreamsBuilder(); final String topic1 = "topic1"; final KTableImpl<String, Integer, Integer> table1 = (KTableImpl<String, Integer, Integer>) builder...
public long brokerEpoch(int brokerId) { BrokerRegistration brokerRegistration = broker(brokerId); if (brokerRegistration == null) { return -1L; } return brokerRegistration.epoch(); }
@Test public void testBrokerEpoch() { assertEquals(123L, IMAGE1.brokerEpoch(2)); }
public static Format of(final FormatInfo formatInfo) { final Format format = fromName(formatInfo.getFormat().toUpperCase()); format.validateProperties(formatInfo.getProperties()); return format; }
@Test public void shouldNotThrowWhenCreatingFromSupportedProperty() { // Given: final FormatInfo avroFormatInfo = FormatInfo.of("AVRO", ImmutableMap.of("schemaId", "1", "fullSchemaName", "avroName")); final FormatInfo protobufFormatInfo = FormatInfo.of("PROTOBUF", ImmutableMap.of("schemaId...
@Override public long extract(final Object key, final GenericRow value) { final String colValue = (String) extractor.extract(key, value); try { return timestampParser.parse(colValue); } catch (final KsqlException e) { throw new KsqlException("Unable to parse string timestamp." + " t...
@SuppressFBWarnings("RV_RETURN_VALUE_IGNORED_NO_SIDE_EFFECT") @Test public void shouldPassRecordToColumnExtractor() { // When: extractor.extract(key, value); // Then: verify(columnExtractor).extract(key, value); }
@Nullable public String remoteServiceName() { return remoteServiceName; }
@Test void remoteServiceNameCoercesEmptyToNull() { MutableSpan span = new MutableSpan(); span.remoteServiceName("FavStar"); span.remoteServiceName(""); assertThat(span.remoteServiceName()).isNull(); }
public static CoderProvider fromStaticMethods(Class<?> rawType, Class<?> coderClazz) { checkArgument( Coder.class.isAssignableFrom(coderClazz), "%s is not a subtype of %s", coderClazz.getName(), Coder.class.getSimpleName()); return new CoderProviderFromStaticMethods(rawType, code...
@Test public void testCoderProvidersFromStaticMethodsForParameterlessTypes() throws Exception { CoderProvider factory = CoderProviders.fromStaticMethods(String.class, StringUtf8Coder.class); assertEquals( StringUtf8Coder.of(), factory.coderFor(TypeDescriptors.strings(), Collections.emptyList())); ...
static void checkManifestPlatform( BuildContext buildContext, ContainerConfigurationTemplate containerConfig) throws PlatformNotFoundInBaseImageException { Optional<Path> path = buildContext.getBaseImageConfiguration().getTarPath(); String baseImageName = path.map(Path::toString) ...
@Test public void testCheckManifestPlatform_tarBaseImage() { Path tar = Paths.get("/foo/bar.tar"); Mockito.when(buildContext.getBaseImageConfiguration()) .thenReturn(ImageConfiguration.builder(ImageReference.scratch()).setTarPath(tar).build()); Mockito.when(containerConfig.getPlatforms()) ...
public static void removeMostServicingBrokersForNamespace( final String assignedBundleName, final Set<String> candidates, final ConcurrentOpenHashMap<String, ConcurrentOpenHashMap<String, ConcurrentOpenHashSet<String>>> brokerToNamespaceToBundleRange) { if...
@Test public void testRemoveMostServicingBrokersForNamespace() { String namespace = "tenant1/ns1"; String assignedBundle = namespace + "/0x00000000_0x40000000"; Set<String> candidates = new HashSet<>(); ConcurrentOpenHashMap<String, ConcurrentOpenHashMap<String, ConcurrentOpenHashSe...
@Override public void execute(Exchange exchange) throws SmppException { SubmitMulti[] submitMulties = createSubmitMulti(exchange); List<SubmitMultiResult> results = new ArrayList<>(submitMulties.length); for (SubmitMulti submitMulti : submitMulties) { SubmitMultiResult result; ...
@Test public void execute() throws Exception { Exchange exchange = new DefaultExchange(new DefaultCamelContext(), ExchangePattern.InOut); exchange.getIn().setHeader(SmppConstants.COMMAND, "SubmitMulti"); exchange.getIn().setHeader(SmppConstants.ID, "1"); exchange.getIn().setHeader(Sm...
@Override public void accept(ServerWebExchange exchange, CachedResponse cachedResponse) { ServerHttpResponse response = exchange.getResponse(); long calculatedMaxAgeInSeconds = calculateMaxAgeInSeconds(exchange.getRequest(), cachedResponse, configuredTimeToLive); rewriteCacheControlMaxAge(response.getHeaders...
@Test void maxAgeIsZero_whenTimeToLiveIsNegative() { inputExchange.getResponse().getHeaders().setCacheControl((String) null); Duration timeToLive = Duration.ofSeconds(-1); CachedResponse inputCachedResponse = CachedResponse.create(HttpStatus.OK).timestamp(clock.instant()).build(); SetMaxAgeHeaderAfterCacheEx...
static InMemorySymbolTable generate(SymbolTableNameHandler symbolTableNameHandler, Set<DataSchema> resourceSchemas) { Set<String> symbols = new HashSet<>(); addFrameworkSymbols(symbols); Set<DataSchema> frameworkSchemas = new HashSet<>(); collectFrameworkSchemas(frameworkSchemas); Set<DataSchema>...
@Test public void testSymbolTableGenerator() { DataSchema schema = DataTemplateUtil.getSchema(SimpleGreeting.class); SymbolTableNameHandler handler = new SymbolTableNameHandler("Haha", "https://localhost:1000/service"); InMemorySymbolTable symbolTable = RuntimeSymbolTableGenerator.generate(handler, Coll...
public static DynamicThreadPoolExecutor buildDynamicPool(ThreadPoolInitParam initParam) { Assert.notNull(initParam); DynamicThreadPoolExecutor dynamicThreadPoolExecutor; try { dynamicThreadPoolExecutor = new DynamicThreadPoolExecutor( initParam.getCorePoolNum(), ...
@Test public void testBuildDynamicPool() { initParam.setWaitForTasksToCompleteOnShutdown(true); initParam.setAwaitTerminationMillis(5000L); ThreadPoolExecutor executor = AbstractBuildThreadPoolTemplate.buildDynamicPool(initParam); AtomicInteger count = new AtomicInteger(0); e...
static boolean isValidIfPresent(@Nullable String email) { return isEmpty(email) || isValidEmail(email); }
@Test public void various_examples_of_unusual_but_valid_emails() { assertThat(isValidIfPresent("info@sonarsource.com")).isTrue(); assertThat(isValidIfPresent("guillaume.jambet+sonarsource-emailvalidatortest@gmail.com")).isTrue(); assertThat(isValidIfPresent("webmaster@kiné-beauté.fr")).isTrue(); asser...
@Nonnull public List<String> value() { return parsedValue; }
@Test void valueWithHttpProtocol() { final RemoteReindexAllowlist allowlist = new RemoteReindexAllowlist(URI.create("http://example.com:9200"), "http://example.com:9200"); Assertions.assertThat(allowlist.value()) .hasSize(1) .contains("example.com:9200"); }
@Override public String load(ImageTarball imageTarball, Consumer<Long> writtenByteCountListener) throws InterruptedException, IOException { // Runs 'docker load'. Process dockerProcess = docker("load"); try (NotifyingOutputStream stdin = new NotifyingOutputStream(dockerProcess.getOutputStre...
@Test public void testLoad_stdinFail() throws InterruptedException { DockerClient testDockerClient = new CliDockerClient(ignored -> mockProcessBuilder); Mockito.when(mockProcess.getOutputStream()) .thenReturn( new OutputStream() { @Override public void write(i...
@Override public DeviceEvent markOffline(DeviceId deviceId) { return markOffline(deviceId, deviceClockService.getTimestamp(deviceId)); }
@Test public final void testMarkOffline() { putDevice(DID1, SW1); assertTrue(deviceStore.isAvailable(DID1)); Capture<InternalDeviceEvent> message = Capture.newInstance(); Capture<MessageSubject> subject = Capture.newInstance(); Capture<Function<InternalDeviceEvent, byte[]>>...
@Override public AttributedList<Path> search(final Path workdir, final Filter<Path> filter, final ListProgressListener listener) throws BackgroundException { return session.getFeature(ListService.class).list(workdir, new SearchListProgressListener(filter, listener)).filter(filter); }
@Test public void testSearch() throws Exception { final Path workdir = new Path("/", EnumSet.of(Path.Type.directory)); final Path f1 = new Path(workdir, "f1", EnumSet.of(Path.Type.file)); final Path f2 = new Path(workdir, "f2", EnumSet.of(Path.Type.file)); final DefaultSearchFeature ...
public static String toLowerHex(long v) { char[] data = RecyclableBuffers.parseBuffer(); writeHexLong(data, 0, v); return new String(data, 0, 16); }
@Test void toLowerHex_midValue() { assertThat(toLowerHex(3405691582L)).isEqualTo("00000000cafebabe"); }
@Override public HealthStatus getStatus() { if (cr.getStatus() == ComponentStatus.INITIALIZING) return HealthStatus.INITIALIZING; PartitionHandlingManager partitionHandlingManager = cr.getComponent(PartitionHandlingManager.class); if (!isComponentHealthy() || partitionHandlingManager.getAvailabili...
@Test public void testUnhealthyStatusWithDegradedPartition() { //given ComponentRegistry componentRegistryMock = mock(ComponentRegistry.class); doReturn(ComponentStatus.RUNNING).when(componentRegistryMock).getStatus(); PartitionHandlingManager partitionHandlingManagerMock = mock(Pa...
@Override public String stem(String word) { b = word.toCharArray(); k = word.length() - 1; if (k > 1) { step1(); step2(); step3(); step4(); step5(); step6(); } return new String(b, 0, k+1); }
@Test public void testStem() { System.out.println("stem"); String[] words = {"consign", "consigned", "consigning", "consignment", "consist", "consisted", "consistency", "consistent", "consistently", "consisting", "consists", "consolation", "consolations", "consolatory", ...