focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override public Flux<ReactiveRedisConnection.BooleanResponse<RenameCommand>> renameNX(Publisher<RenameCommand> commands) { return execute(commands, command -> { Assert.notNull(command.getKey(), "Key must not be null!"); Assert.notNull(command.getNewName(), "New name must not be null...
@Test public void testRenameNX() { connection.stringCommands().set(originalKey, value).block(); if (hasTtl) { connection.keyCommands().expire(originalKey, Duration.ofSeconds(1000)).block(); } Integer originalSlot = getSlotForKey(originalKey); newKey = getNewKeyFo...
public static Read read() { return new AutoValue_RabbitMqIO_Read.Builder() .setQueueDeclare(false) .setExchangeDeclare(false) .setMaxReadTime(null) .setMaxNumRecords(Long.MAX_VALUE) .setUseCorrelationId(false) .build(); }
@Test(expected = Pipeline.PipelineExecutionException.class) public void testQueueDeclareWithoutQueueNameFails() throws Exception { RabbitMqIO.Read read = RabbitMqIO.read().withQueueDeclare(true); doExchangeTest(new ExchangeTestPlan(read, 1)); }
@Override public boolean commitRequested() { return task.commitRequested(); }
@Test public void shouldDelegateCommitRequested() { final ReadOnlyTask readOnlyTask = new ReadOnlyTask(task); readOnlyTask.commitRequested(); verify(task).commitRequested(); }
public static DataflowRunner fromOptions(PipelineOptions options) { DataflowPipelineOptions dataflowOptions = PipelineOptionsValidator.validate(DataflowPipelineOptions.class, options); ArrayList<String> missing = new ArrayList<>(); if (dataflowOptions.getAppName() == null) { missing.add("appN...
@Test public void testGcsStagingLocationInitialization() throws Exception { // Set temp location (required), and check that staging location is set. DataflowPipelineOptions options = PipelineOptionsFactory.as(DataflowPipelineOptions.class); options.setTempLocation(VALID_TEMP_BUCKET); options.setProjec...
@Override public String getBookmark() { final String path = this.getAbbreviatedPath(); String bookmark = PreferencesFactory.get().getProperty(String.format("local.bookmark.%s", path)); if(StringUtils.isBlank(bookmark)) { try { bookmark = resolver.create(this); ...
@Test public void testBookmark() throws Exception { FinderLocal l = new FinderLocal(System.getProperty("user.dir"), UUID.randomUUID().toString(), new AliasFilesystemBookmarkResolver()); assertNull(l.getBookmark()); new DefaultLocalTouchFeature().touch(l); assertNotNull(l.getBookmark(...
@SuppressWarnings("checkstyle:MissingSwitchDefault") @Override protected void doCommit(TableMetadata base, TableMetadata metadata) { int version = currentVersion() + 1; CommitStatus commitStatus = CommitStatus.FAILURE; /* This method adds no fs scheme, and it persists in HTS that way. */ final Stri...
@Test void testDoCommitDeleteSnapshots() throws IOException { List<Snapshot> testSnapshots = IcebergTestUtil.getSnapshots(); // add all snapshots to the base metadata TableMetadata base = BASE_TABLE_METADATA; for (Snapshot snapshot : testSnapshots) { base = TableMetadata.buildFrom(base...
@Nullable public static String getXID() { return (String) CONTEXT_HOLDER.get(KEY_XID); }
@Test public void testGetXID() { RootContext.bind(DEFAULT_XID); assertThat(RootContext.getXID()).isEqualTo(DEFAULT_XID); assertThat(RootContext.unbind()).isEqualTo(DEFAULT_XID); assertThat(RootContext.getXID()).isNull(); }
@Override public void write(T record) { recordConsumer.startMessage(); try { messageWriter.writeTopLevelMessage(record); } catch (RuntimeException e) { Message m = (record instanceof Message.Builder) ? ((Message.Builder) record).build() : (Message) record; LOG.error("Cannot write message...
@Test public void testMapRecursion() { RecordConsumer readConsumerMock = Mockito.mock(RecordConsumer.class); Configuration conf = new Configuration(); ProtoSchemaConverter.setMaxRecursion(conf, 1); ProtoWriteSupport<Value> spyWriter = createReadConsumerInstance(Value.class, readConsumerMock, conf); ...
protected GelfMessage toGELFMessage(final Message message) { final DateTime timestamp; final Object fieldTimeStamp = message.getField(Message.FIELD_TIMESTAMP); if (fieldTimeStamp instanceof DateTime) { timestamp = (DateTime) fieldTimeStamp; } else { timestamp = To...
@Test public void testToGELFMessageWithValidNumericLevel() throws Exception { final GelfTransport transport = mock(GelfTransport.class); final GelfOutput gelfOutput = new GelfOutput(transport); final DateTime now = DateTime.now(DateTimeZone.UTC); final Message message = messageFactor...
@GetMapping() @Secured(resource = AuthConstants.CONSOLE_RESOURCE_NAME_PREFIX + "namespaces", action = ActionTypes.READ, signType = SignType.CONSOLE) public Result<Namespace> getNamespace(@RequestParam("namespaceId") String namespaceId) throws NacosException { return Result.success(namespaceO...
@Test void testGetNamespace() throws NacosException { Namespace namespaceAllInfo = new Namespace(TEST_NAMESPACE_ID, TEST_NAMESPACE_NAME, TEST_NAMESPACE_DESC, 200, 1, NamespaceTypeEnum.GLOBAL.getType()); when(namespaceOperationService.getNamespace(TEST_NAMESPACE_ID)).thenReturn(namesp...
public static InlineExpressionParser newInstance(final String inlineExpression) { Properties props = new Properties(); if (null == inlineExpression) { return TypedSPILoader.getService(InlineExpressionParser.class, DEFAULT_TYPE_NAME, props); } if (!inlineExpression.startsWith(...
@Test void assertUndefinedInstance() { assertThrows(ServiceProviderNotFoundException.class, () -> InlineExpressionParserFactory.newInstance("<UNDEFINED>t_order_0, t_order_1").getType()); }
public int doWork() { final long nowNs = nanoClock.nanoTime(); trackTime(nowNs); int workCount = 0; workCount += processTimers(nowNs); if (!asyncClientCommandInFlight) { workCount += clientCommandAdapter.receive(); } workCount += drainComm...
@Test void shouldErrorWhenConflictingReliableSubscriptionAdded() { driverProxy.addSubscription(CHANNEL_4000 + "|reliable=false", STREAM_ID_1); driverConductor.doWork(); final long id2 = driverProxy.addSubscription(CHANNEL_4000 + "|reliable=true", STREAM_ID_1); driverConductor.do...
@Override public Locator locator() { return inner.locator(); }
@Test public void shouldReturnInnerLocator() { // Given: final Locator expected = mock(Locator.class); when(inner.locator()).thenReturn(expected); givenNoopTransforms(); // When: final Locator locator = materialization.locator(); // Then: assertThat(locator, is(sameInstance(expected)...
public String destinationURL(File rootPath, File file) { return destinationURL(rootPath, file, getSrc(), getDest()); }
@Test public void shouldProvideAppendFilePathToDest() { ArtifactPlan artifactPlan = new ArtifactPlan(ArtifactPlanType.file, "test/**/*/a.log", "logs"); assertThat(artifactPlan.destinationURL(new File("pipelines/pipelineA"), new File("pipelines/pipelineA/test/a/b/a.log"))).isEqualTo("logs...
String name(String name) { return sanitize(name, NAME_RESERVED); }
@Test public void truncatesNamesExceedingMaxLength() throws Exception { String longName = "01234567890123456789012345678901234567890123456789012345678901234567890123456789"; assertThat(sanitize.name(longName)).isEqualTo(longName.substring(0, (Sanitize.DEFAULT_MAX_LENGTH))); }
@PostMapping() @Secured(action = ActionTypes.WRITE, signType = SignType.CONFIG) public Result<Boolean> publishConfig(ConfigForm configForm, HttpServletRequest request) throws NacosException { // check required field configForm.validate(); String encryptedDataKeyFinal = configForm.getEncr...
@Test void testPublishConfigWithEncryptedDataKey() throws Exception { ConfigForm configForm = new ConfigForm(); configForm.setDataId(TEST_DATA_ID); configForm.setGroup(TEST_GROUP); configForm.setNamespaceId(TEST_NAMESPACE_ID); configForm.setContent(TEST_CONTENT); ...
public long getMinOffset(final String addr, final MessageQueue messageQueue, final long timeoutMillis) throws RemotingException, MQBrokerException, InterruptedException { GetMinOffsetRequestHeader requestHeader = new GetMinOffsetRequestHeader(); requestHeader.setTopic(messageQueue.getTopic()); ...
@Test public void testGetMinOffset() throws Exception { doAnswer((Answer<RemotingCommand>) mock -> { RemotingCommand request = mock.getArgument(1); final RemotingCommand response = RemotingCommand.createResponseCommand(GetMinOffsetResponseHeader.class); final GetMinOffse...
@Override public void apply(Project project) { checkGradleVersion(project); project.getPlugins().apply(JavaPlugin.class); // this HashMap will have a PegasusOptions per sourceSet project.getExtensions().getExtraProperties().set("pegasus", new HashMap<>()); // this map will extract PegasusOptio...
@Test public void test() { Project project = ProjectBuilder.builder().build(); project.getPlugins().apply(PegasusPlugin.class); assertTrue(project.getPlugins().hasPlugin(JavaPlugin.class)); // if any configuration is resolved in configuration phase, user script that tries to exclude certain depend...
@SuppressWarnings({"unchecked", "rawtypes"}) public static <T> List<T> sort(List<T> list) { if (isNotEmpty(list)) { Collections.sort((List) list); } return list; }
@Test void testSort() { List<Integer> list = new ArrayList<Integer>(); list.add(100); list.add(10); list.add(20); List<Integer> expected = new ArrayList<Integer>(); expected.add(10); expected.add(20); expected.add(100); assertEquals(expected,...
public static DataSource createDataSource(final File yamlFile) throws SQLException, IOException { YamlJDBCConfiguration rootConfig = YamlEngine.unmarshal(yamlFile, YamlJDBCConfiguration.class); return createDataSource(new YamlDataSourceConfigurationSwapper().swapToDataSources(rootConfig.getDataSources()...
@Test void assertCreateDataSourceWithFileForExternalSingleDataSource() throws Exception { assertDataSource(YamlShardingSphereDataSourceFactory.createDataSource(new MockedDataSource(), new File(getYamlFileUrl().toURI()))); }
public OpenAPI read(Class<?> cls) { return read(cls, resolveApplicationPath(), null, false, null, null, new LinkedHashSet<String>(), new ArrayList<Parameter>(), new HashSet<Class<?>>()); }
@Test(description = "SecurityScheme with REf") public void testSecuritySchemeWithRef() { Components components = new Components(); components.addSecuritySchemes("Security", new SecurityScheme().description("Security Example"). name("Security").type(SecurityScheme.Type.OAUTH2).$ref("m...
@Override @MethodNotAvailable public void close() { throw new MethodNotAvailableException(); }
@Test(expected = MethodNotAvailableException.class) public void testClose() { adapter.close(); }
@Override public Path mkdir(final Path folder, final TransferStatus status) throws BackgroundException { try { session.getClient().createDirectory(new DAVPathEncoder().encode(folder)); } catch(SardineException e) { throw new DAVExceptionMappingService().map("Cannot cr...
@Test public void testMakeDirectory() throws Exception { final Path test = new Path(new DefaultHomeFinderService(session).find(), new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory)); new DAVDirectoryFeature(session).mkdir(test, new TransferStatus()); assertTrue(s...
public List<String> splitSql(String text) { List<String> queries = new ArrayList<>(); StringBuilder query = new StringBuilder(); char character; boolean multiLineComment = false; boolean singleLineComment = false; boolean singleQuoteString = false; boolean doubleQuoteString = false; fo...
@Test void testCustomSplitter_1() { SqlSplitter sqlSplitter = new SqlSplitter("//"); List<String> sqls = sqlSplitter.splitSql("show tables;\n//comment_1"); assertEquals(1, sqls.size()); assertEquals("show tables", sqls.get(0)); sqls = sqlSplitter.splitSql("show tables;\n//comment_1"); assertE...
public MessageListener messageListener(MessageListener messageListener, boolean addConsumerSpan) { if (messageListener instanceof TracingMessageListener) return messageListener; return new TracingMessageListener(messageListener, this, addConsumerSpan); }
@Test void messageListener_traces_addsConsumerSpan() { jmsTracing.messageListener(mock(MessageListener.class), true) .onMessage(message); assertThat( asList(testSpanHandler.takeRemoteSpan(Kind.CONSUMER), testSpanHandler.takeLocalSpan())) .extracting(brave.handler.MutableSpan::name) .con...
@Override public void filter(ContainerRequestContext requestContext) throws IOException { ThreadContext.unbindSubject(); final boolean secure = requestContext.getSecurityContext().isSecure(); final MultivaluedMap<String, String> headers = requestContext.getHeaders(); final Map<String...
@Test(expected = BadRequestException.class) public void filterWithMalformedBasicAuthShouldThrowBadRequestException() throws Exception { final MultivaluedHashMap<String, String> headers = new MultivaluedHashMap<>(); headers.putSingle(HttpHeaders.AUTHORIZATION, "Basic ****"); when(requestConte...
@Override public Collection<Event> filter(Collection<Event> events, final FilterMatchListener filterMatchListener) { for (Event e : events) { if (overwrite || e.getField(target) == null) { e.setField(target, UUID.randomUUID().toString()); } filterMatchList...
@Test public void testUuidWithOverwrite() { String targetField = "target_field"; String originalValue = "originalValue"; Map<String, Object> rawConfig = new HashMap<>(); rawConfig.put(Uuid.TARGET_CONFIG.name(), targetField); rawConfig.put(Uuid.OVERWRITE_CONFIG.name(), true); ...
public static void checkHttpTimeoutProperty() throws NumberFormatException { checkNumericSystemProperty(HTTP_TIMEOUT, Range.atLeast(0)); }
@Test public void testCheckHttpTimeoutProperty_stringValue() { System.setProperty(JibSystemProperties.HTTP_TIMEOUT, "random string"); try { JibSystemProperties.checkHttpTimeoutProperty(); Assert.fail(); } catch (NumberFormatException ex) { Assert.assertEquals("jib.httpTimeout must be an ...
@PostMapping("/authorize") @Operation(summary = "申请授权", description = "适合 code 授权码模式,或者 implicit 简化模式;在 sso.vue 单点登录界面被【提交】调用") @Parameters({ @Parameter(name = "response_type", required = true, description = "响应类型", example = "code"), @Parameter(name = "client_id", required = true, descr...
@Test public void testApproveOrDeny_grantTypeError() { // 调用,并断言 assertServiceException(() -> oauth2OpenController.approveOrDeny(randomString(), null, null, null, null, null), new ErrorCode(400, "response_type 参数值只允许 code 和 token")); }
public ServiceInfo processServiceInfo(String json) { ServiceInfo serviceInfo = JacksonUtils.toObj(json, ServiceInfo.class); serviceInfo.setJsonFromServer(json); return processServiceInfo(serviceInfo); }
@Test void testProcessNullServiceInfo() { assertNull(holder.processServiceInfo(new ServiceInfo())); }
public static String getRuleName(final String ruleRow) { String testVal = ruleRow.toLowerCase(); final int left = testVal.indexOf( DefaultRuleSheetListener.RULE_TABLE_TAG ); return ruleRow.substring( left + DefaultRuleSheetListener.RULE_TABLE_TAG.length() ).trim(); }
@Test public void testRuleName() { final String row = " RuleTable This is my rule name"; final String result = getRuleName(row); assertThat(result).isEqualTo("This is my rule name"); }
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...
@Test public void testActivateWorkForKey_matchingCacheTokens_newWorkTokenGreater_queuedWorkNotActive_QUEUED() { long matchingCacheToken = 1L; long newWorkToken = 10L; long queuedWorkToken = newWorkToken / 2; ShardedKey shardedKey = shardedKey("someKey", 1L); ExecutableWork differentWorkToke...
private OperationNode createParDoOperation( Network<Node, Edge> network, ParallelInstructionNode node, PipelineOptions options, DataflowExecutionContext<?> executionContext, DataflowOperationContext operationContext) throws Exception { ParallelInstruction instruction = node.getP...
@Test public void testCreateParDoOperation() throws Exception { int producerIndex = 1; int producerOutputNum = 2; BatchModeExecutionContext context = BatchModeExecutionContext.forTesting(options, counterSet, "testStage"); ParallelInstructionNode instructionNode = ParallelInstructionNo...
@PostMapping public AccountLogsResult getAccountLogs(@RequestBody @Valid AccountLogsRequest request, @RequestHeader(MijnDigidSession.MIJN_DIGID_SESSION_HEADER) String mijnDigiDsessionId){ MijnDigidSession mijnDigiDSession = retrieveMijnDigiDSession(mijnDigiDsessio...
@Test public void testValidRequest() { AccountLogsRequest request = new AccountLogsRequest(); request.setPageId(1); AccountLogsResult result = new AccountLogsResult(); result.setTotalItems(10); result.setTotalPages(1); List<AccountLog> results = new ArrayList<>(); ...
@Override public ContinuousEnumerationResult planSplits(IcebergEnumeratorPosition lastPosition) { table.refresh(); if (lastPosition != null) { return discoverIncrementalSplits(lastPosition); } else { return discoverInitialSplits(); } }
@Test public void testIncrementalFromEarliestSnapshotWithNonEmptyTable() throws Exception { appendTwoSnapshots(); ScanContext scanContext = ScanContext.builder() .startingStrategy(StreamingStartingStrategy.INCREMENTAL_FROM_EARLIEST_SNAPSHOT) .build(); ContinuousSplitPlanne...
void buildPhysicalTopology() throws Exception { if (CollectionUtils.isNotEmpty(plan.getFragments()) && plan.getTopFragment().getSink() instanceof OlapTableSink) { ConnectContext context = queryCoordinator.getConnectContext(); context.getSessionVariable().setPreferComputeN...
@Test public void buildPhysicalTopology() throws Exception { String sql = "select count(distinct v5) from t1 join t2"; Pair<String, ExecPlan> pair = UtFrameUtils.getPlanAndFragment(connectContext, sql); assertEquals("AGGREGATE ([GLOBAL] aggregate [{7: count=count(7: count)}] group by [[]] ha...
@Override public DescribeShareGroupsResult describeShareGroups(final Collection<String> groupIds, final DescribeShareGroupsOptions options) { SimpleAdminApiFuture<CoordinatorKey, ShareGroupDescription> future = DescribeShareGroupsHandl...
@Test public void testDescribeShareGroupsWithAuthorizedOperationsOmitted() throws Exception { try (AdminClientUnitTestEnv env = new AdminClientUnitTestEnv(mockCluster(1, 0))) { env.kafkaClient().setNodeApiVersions(NodeApiVersions.create()); env.kafkaClient().prepareResponse( ...
public static ObjectNode convertFromGHResponse(GHResponse ghResponse, TranslationMap translationMap, Locale locale, DistanceConfig distanceConfig) { ObjectNode json = JsonNodeFactory.instance.objectNode(); if (ghResponse.hasErrors()) throw new IllegalStateException( ...
@Test public void testMultipleWaypoints() { GHRequest request = new GHRequest(); request.addPoint(new GHPoint(42.504606, 1.522438)); request.addPoint(new GHPoint(42.504776, 1.527209)); request.addPoint(new GHPoint(42.505144, 1.526113)); request.addPoint(new GHPoint(42.50529,...
@Override public Map<String, Object> assembleFrom(OAuth2AccessTokenEntity accessToken, UserInfo userInfo, Set<String> authScopes) { Map<String, Object> result = newLinkedHashMap(); OAuth2Authentication authentication = accessToken.getAuthenticationHolder().getAuthentication(); result.put(ACTIVE, true); if (...
@Test public void shouldAssembleExpectedResultForAccessTokenWithoutUserInfo() throws ParseException { // given OAuth2AccessTokenEntity accessToken = accessToken(new Date(123 * 1000L), scopes("foo", "bar"), null, "Bearer", oauth2AuthenticationWithUser(oauth2Request("clientId"), "name")); Set<String> authSco...
public void updateConsumeOffset(MessageQueue mq, long offset) { this.brokerController.getConsumerOffsetManager().commitOffset( RemotingHelper.parseSocketAddressAddr(this.storeHost), TransactionalMessageUtil.buildConsumerGroup(), mq.getTopic(), mq.getQueueId(), offset); }
@Test public void updateConsumeOffset() { MessageQueue mq = new MessageQueue(TransactionalMessageUtil.buildOpTopic(), this.brokerController.getBrokerConfig().getBrokerName(), 0); transactionBridge.updateConsumeOffset(mq, 0); }
public ValidationResult validate(final Map<String, InternalTopicConfig> topicConfigs) { log.info("Starting to validate internal topics {}.", topicConfigs.keySet()); final long now = time.milliseconds(); final long deadline = now + retryTimeoutMs; final ValidationResult validationResult...
@Test public void shouldThrowTimeoutExceptionWhenFuturesNeverCompleteDuringValidation() { final AdminClient admin = mock(AdminClient.class); final MockTime time = new MockTime( (Integer) config.get(StreamsConfig.consumerPrefix(ConsumerConfig.MAX_POLL_INTERVAL_MS_CONFIG)) / 3 ); ...
public static StatementExecutorResponse execute( final ConfiguredStatement<DropConnector> statement, final SessionProperties sessionProperties, final KsqlExecutionContext executionContext, final ServiceContext serviceContext ) { final String connectorName = statement.getStatement().getConn...
@Test public void shouldPassInCorrectArgsToConnectClient() { // Given: when(connectClient.delete(anyString())) .thenReturn(ConnectResponse.success("foo", HttpStatus.SC_OK)); // When: DropConnectorExecutor.execute(DROP_CONNECTOR_CONFIGURED, mock(SessionProperties.class),null, serviceContext); ...
@Override public Collection<String> generateKeys(final AlgorithmSQLContext context, final int keyGenerateCount) { Collection<String> result = new LinkedList<>(); ThreadLocalRandom threadLocalRandom = ThreadLocalRandom.current(); for (int index = 0; index < keyGenerateCount; index++) { ...
@Test void assertGenerateKeys() { assertThat(algorithm.generateKeys(mock(AlgorithmSQLContext.class), 1).size(), is(1)); assertThat(algorithm.generateKeys(mock(AlgorithmSQLContext.class), 1).iterator().next().length(), is(32)); }
@VisibleForTesting static List<String> tokenizeArguments(@Nullable final String args) { if (args == null) { return Collections.emptyList(); } final Matcher matcher = ARGUMENTS_TOKENIZE_PATTERN.matcher(args); final List<String> tokens = new ArrayList<>(); while (ma...
@Test void testTokenizeNonQuoted() { final List<String> arguments = JarHandlerUtils.tokenizeArguments("--foo bar"); assertThat(arguments.get(0)).isEqualTo("--foo"); assertThat(arguments.get(1)).isEqualTo("bar"); }
@Override public Serializable read(final MySQLBinlogColumnDef columnDef, final MySQLPacketPayload payload) { int time = payload.getByteBuf().readUnsignedMedium(); if (0x800000 == time) { return MySQLTimeValueUtils.ZERO_OF_TIME; } MySQLFractionalSeconds fractionalSeconds =...
@Test void assertReadWithFraction1() { columnDef.setColumnMeta(1); when(payload.getByteBuf()).thenReturn(byteBuf); when(payload.readInt1()).thenReturn(90); when(byteBuf.readUnsignedMedium()).thenReturn(0x800000 | (0x10 << 12) | (0x08 << 6) | 0x04); assertThat(new MySQLTime2Bi...
@Override public TableDataConsistencyCheckResult swapToObject(final YamlTableDataConsistencyCheckResult yamlConfig) { if (null == yamlConfig) { return null; } if (!Strings.isNullOrEmpty(yamlConfig.getIgnoredType())) { return new TableDataConsistencyCheckResult(TableDa...
@Test void assertSwapToObjectWithYamlTableDataConsistencyCheckResultIgnoredType() { YamlTableDataConsistencyCheckResult yamlConfig = new YamlTableDataConsistencyCheckResult(); yamlConfig.setIgnoredType("NO_UNIQUE_KEY"); TableDataConsistencyCheckResult actual = yamlTableDataConsistencyCheckRe...
@Override public boolean betterThan(Num criterionValue1, Num criterionValue2) { return lessIsBetter ? criterionValue1.isLessThan(criterionValue2) : criterionValue1.isGreaterThan(criterionValue2); }
@Test public void betterThanWithLessIsBetter() { AnalysisCriterion criterion = getCriterion(); assertTrue(criterion.betterThan(numOf(3), numOf(6))); assertFalse(criterion.betterThan(numOf(7), numOf(4))); }
public ValidationResult validate(final Map<String, InternalTopicConfig> topicConfigs) { log.info("Starting to validate internal topics {}.", topicConfigs.keySet()); final long now = time.milliseconds(); final long deadline = now + retryTimeoutMs; final ValidationResult validationResult...
@Test public void shouldNotThrowExceptionIfTopicExistsWithDifferentReplication() { setupTopicInMockAdminClient(topic1, repartitionTopicConfig()); // attempt to create it again with replication 1 final InternalTopicManager internalTopicManager2 = new InternalTopicManager( time, ...
@Override public Object unbox() { switch (type) { case STRING_ARRAY: String[] arrays = new String[val.length]; for (int i = 0; i < arrays.length; ++i) { arrays[i] = ((SelString) val[i]).getInternalVal(); } return arrays; case LONG_ARRAY: long[] arrayl ...
@Test public void unbox() { assertArrayEquals(new String[] {"foo", "bar"}, (String[]) one.unbox()); assertArrayEquals(new long[] {1, 2, 3}, (long[]) another.unbox()); }
public void runExtractor(Message msg) { try(final Timer.Context ignored = completeTimer.time()) { final String field; try (final Timer.Context ignored2 = conditionTimer.time()) { // We can only work on Strings. if (!(msg.getField(sourceField) instanceof St...
@Test public void testWithNullResult() throws Exception { final TestExtractor extractor = new TestExtractor.Builder() .callback(new Callable<Result[]>() { @Override public Result[] call() throws Exception { return null; ...
void runOnce() { if (transactionManager != null) { try { transactionManager.maybeResolveSequences(); RuntimeException lastError = transactionManager.lastError(); // do not continue sending if the transaction manager is in a failed state ...
@Test public void testInitProducerIdWithMaxInFlightOne() { final long producerId = 123456L; createMockClientWithMaxFlightOneMetadataPending(); // Initialize transaction manager. InitProducerId will be queued up until metadata response // is processed and FindCoordinator can be sent ...
@Override public String named() { return PluginEnum.GENERAL_CONTEXT.getName(); }
@Test public void tesNamed() { assertEquals(this.generalContextPlugin.named(), PluginEnum.GENERAL_CONTEXT.getName()); }
public List<String> parse(final CharSequence line) { return this.lineParser.parse( line.toString() ); }
@Test public void testLineParse() { final CsvLineParser parser = new CsvLineParser(); final String s = "a,\"b\",c"; final List<String> list = parser.parse(s); assertThat(list).hasSize(3).containsExactly("a", "b", "c"); }
@Udf public int field( @UdfParameter final String str, @UdfParameter final String... args ) { if (str == null || args == null) { return 0; } for (int i = 0; i < args.length; i++) { if (str.equals(args[i])) { return i + 1; } } return 0; }
@Test public void shouldFindSecondArgument() { // When: final int pos = field.field("world", "hello", "world"); // Then: assertThat(pos, equalTo(2)); }
@Override public Column convert(BasicTypeDefine typeDefine) { PhysicalColumn.PhysicalColumnBuilder builder = PhysicalColumn.builder() .name(typeDefine.getName()) .sourceType(typeDefine.getColumnType()) .nullable(typeDefi...
@Test public void testConvertOtherString() { BasicTypeDefine<Object> typeDefine = BasicTypeDefine.builder().name("test").columnType("text").dataType("text").build(); Column column = PostgresTypeConverter.INSTANCE.convert(typeDefine); Assertions.assertEquals(typeDefine.getName...
public static boolean isFastStatsSame(Partition oldPart, Partition newPart) { // requires to calculate stats if new and old have different fast stats if ((oldPart != null) && oldPart.isSetParameters() && newPart != null && newPart.isSetParameters()) { for (String stat : StatsSetupConst.FAST_STATS) { ...
@Test public void isFastStatsSameNullStatsInNew() { Partition oldPartition = new Partition(); Partition newPartition = new Partition(); Map<String, String> oldParams = new HashMap<>(); Map<String, String> newParams = new HashMap<>(); long testVal = 1; for (String key : FAST_STATS) { oldP...
@Override public SelJodaDateTimeProperty assignOps(SelOp op, SelType rhs) { if (op == SelOp.ASSIGN) { SelTypeUtil.checkTypeMatch(this.type(), rhs.type()); this.val = ((SelJodaDateTimeProperty) rhs).val; return this; } throw new UnsupportedOperationException(type() + " DO NOT support assi...
@Test public void testAssignOps() { assertEquals("DATETIME_PROPERTY: Property[dayOfWeek]", one.type() + ": " + one); one.assignOps(SelOp.ASSIGN, another); assertEquals("DATETIME_PROPERTY: Property[dayOfMonth]", one.type() + ": " + one); }
public String getToken() throws IOException { LOGGER.debug("[Agent Registration] Using URL {} to get a token.", tokenURL); HttpRequestBase getTokenRequest = (HttpRequestBase) RequestBuilder.get(tokenURL) .addParameter("uuid", agentRegistry.uuid()) .build(); try ...
@Test void shouldErrorOutIfServerRejectTheRequest() throws Exception { final CloseableHttpResponse httpResponse = mock(CloseableHttpResponse.class); when(agentRegistry.uuid()).thenReturn("agent-uuid"); when(httpClient.execute(any(HttpRequestBase.class))).thenReturn(httpResponse); wh...
@Override public void onLeaderInformationChange(String componentId, LeaderInformation leaderInformation) { synchronized (lock) { notifyLeaderInformationChangeInternal( componentId, leaderInformation, confirmedLeaderInformation.forCompon...
@Test void testGrantDoesNotBlockNotifyAllKnownLeaderInformation() throws Exception { testLeaderEventDoesNotBlockLeaderInformationChangeEventHandling( (listener, componentId, storedLeaderInformation) -> { listener.onLeaderInformationChange(storedLeaderInformation); ...
@Override public Repository getRepository() { try { // NOTE: this class formerly used a ranking system to prioritize the providers registered and would check them in order // of priority for the first non-null repository. In practice, we only ever registered one at a time, spoon or PUC. // As suc...
@Test public void testGetRepositoryNone() { assertNull( kettleRepositoryLocator.getRepository() ); }
public String extractDeclaredEncoding(byte[] bytes) { int index = ArrayUtils.indexOf(bytes, (byte) '>'); if (index == -1) { return null; } String pi = new String(ArrayUtils.subarray(bytes, 0, index + 1)).replace('\'', '"'); index = StringUtils.indexOf(pi, "encoding=\""); if (index == -1) { return nul...
@Test void testExtractDeclaredEncoding() { Assertions.assertNull(encodingDetector.extractDeclaredEncoding("<?xml ?>".getBytes())); Assertions.assertNull(encodingDetector.extractDeclaredEncoding("<feed></feed>".getBytes())); Assertions.assertEquals("UTF-8", encodingDetector.extractDeclaredEncoding("<?xml encoding...
public static synchronized String getMetric(MetricVisitor visitor, MetricsAction.RequestParams requestParams) { if (!hasInit) { return ""; } // update the metrics first updateMetrics(); // jvm JvmStatCollector jvmStatCollector = new JvmStatCollector(); ...
@Test public void testGetMetric() throws Exception { starRocksAssert.useDatabase("test_metric") .withTable("create table t1 (c1 int, c2 string)" + " distributed by hash(c1) " + " properties('replication_num'='1') "); Table t1 = starRock...
@Override public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException { responseContext.getHeaders().add(X_FRAME_OPTIONS, (httpAllowEmbedding ? EmbeddingOptions.SAMEORIGIN : EmbeddingOptions.DENY).toString()); }
@Test void allowsEmbeddingForSameOriginIfConfigurationSettingIsTrue() throws IOException { final EmbeddingControlFilter filter = new EmbeddingControlFilter(true); final ContainerResponseContext responseContext = new ContainerResponse(requestContext, Response.ok().build()); filter.filter(req...
@Override public V put(final K key, final V value) { final Entry<K, V>[] table = this.table; final int hash = key.hashCode(); final int index = HashUtil.indexFor(hash, table.length, mask); for (Entry<K, V> e = table[index]; e != null; e = e.hashNext) { final K entryKey; ...
@Test public void keySet() { final LinkedHashMap<Integer, String> tested = new LinkedHashMap<>(); for (int i = 0; i < 10000; ++i) { tested.put(i, Integer.toString(i)); } int i = 10000; for (Integer key : tested.keySet()) { Assert.assertEquals(--i, key....
public static void debug(Logger logger, String msg) { if (logger == null) { return; } if (logger.isDebugEnabled()) { logger.debug(msg); } }
@Test void testDebug() { Logger logger = Mockito.mock(Logger.class); when(logger.isDebugEnabled()).thenReturn(true); LogHelper.debug(logger, "debug"); verify(logger).debug("debug"); Throwable t = new RuntimeException(); LogHelper.debug(logger, t); verify(logge...
public static Map<String, String> revertSubscribe(Map<String, String> subscribe) { Map<String, String> newSubscribe = new HashMap<>(); for (Map.Entry<String, String> entry : subscribe.entrySet()) { String serviceName = entry.getKey(); String serviceQuery = entry.getValue(); ...
@Test void testRevertSubscribe() { String key = "perf/dubbo.test.api.HelloService:1.0.0"; Map<String, String> subscribe = new HashMap<String, String>(); subscribe.put(key, null); Map<String, String> newSubscribe = UrlUtils.revertSubscribe(subscribe); Map<String, String> expec...
@Override public <VOut> KStream<K, VOut> processValues( final FixedKeyProcessorSupplier<? super K, ? super V, VOut> processorSupplier, final String... stateStoreNames ) { return processValues( processorSupplier, Named.as(builder.newProcessorName(PROCESSVALUES_NAME...
@Test public void shouldNotAllowNullProcessValuesSupplierOnProcess() { final NullPointerException exception = assertThrows( NullPointerException.class, () -> testStream.processValues((FixedKeyProcessorSupplier<? super String, ? super String, Void>) null)); assertThat(exceptio...
@VisibleForTesting void validateTemplateParams(MailTemplateDO template, Map<String, Object> templateParams) { template.getParams().forEach(key -> { Object value = templateParams.get(key); if (value == null) { throw exception(MAIL_SEND_TEMPLATE_PARAM_MISS, key); ...
@Test public void testValidateTemplateParams_paramMiss() { // 准备参数 MailTemplateDO template = randomPojo(MailTemplateDO.class, o -> o.setParams(Lists.newArrayList("code"))); Map<String, Object> templateParams = new HashMap<>(); // mock 方法 // 调用,并断言异常 a...
@Override public DateTime touch(AccessToken accessToken) throws ValidationException { try { return lastAccessCache.get(accessToken.getId()); } catch (ExecutionException e) { LOG.debug("Ignoring error: " + e.getMessage()); return null; } }
@Test @MongoDBFixtures("accessTokensSingleToken.json") public void testTouch() throws Exception { accessTokenService.setLastAccessCache(1, TimeUnit.NANOSECONDS); final AccessToken token = accessTokenService.load("foobar"); final DateTime firstAccess = accessTokenService.touch(token); ...
@Override public JavaKeyStore create(SecureConfig config) { if (exists(config)) { throw new SecretStoreException.AlreadyExistsException(String.format("Logstash keystore at %s already exists.", new String(config.getPlainText(PATH_KEY)))); } try { in...
@Test public void testEmptyNotAllowedOnCreate() throws IOException { Path altPath = folder.newFolder().toPath().resolve("alt.logstash.keystore"); SecureConfig altConfig = new SecureConfig(); altConfig.add("keystore.file", altPath.toString().toCharArray()); altConfig.add(SecretStoreFa...
@VisibleForTesting long getNumBytesToRead(long fileLength, long position, long bufLength) { if (position + bufLength < fileLength) { return bufLength; } else { return fileLength - position; } }
@Test(timeout = 40000) public void testGetNumBytesToRead() { long pos = 100; long buffLength = 1024; long fileLength = 2058; RetriableFileCopyCommand retriableFileCopyCommand = new RetriableFileCopyCommand("Testing NumBytesToRead ", FileAction.OVERWRITE); long numBy...
@Deprecated public String idFromFilename(@NonNull String filename) { return filename; }
@SuppressWarnings("deprecation") @Test public void caseInsensitivePassesThroughOldLegacy() { IdStrategy idStrategy = new IdStrategy.CaseInsensitive(); assertThat(idStrategy.idFromFilename("make\u1000000"), is("make\u1000000")); assertThat(idStrategy.idFromFilename("\u306f\u56fd\u5185\u3...
public static boolean validMagicNumbers( final BufferedInputStream bin ) throws IOException { final List<String> validMagicBytesCollection = JiveGlobals.getListProperty( "plugins.upload.magic-number.values.expected-value", Arrays.asList( "504B0304", "504B0506", "504B0708" ) ); for ( final String ent...
@Test public void testTxtMagicBytes() throws Exception { // Setup test fixture. try (final InputStream inputStream = getClass().getClassLoader().getResourceAsStream( "fullchain.pem" )) { assert inputStream != null; try (final BufferedInputStream in = new BufferedInputStre...
public static int getLength(byte[] raw) { try (final Asn1InputStream is = new Asn1InputStream(raw)) { is.readTag(); return is.readLength(); } }
@Test public void getLengthSingleByte() { final byte[] data = new byte[0x7f]; final byte[] obj = Arrays.concatenate(new byte[] { 0x10, (byte) 0x7f }, data); assertEquals(0x7f, Asn1Utils.getLength(obj)); }
@Override public Result responseMessageForCheckout(String responseBody) { return jsonResultMessageHandler.toResult(responseBody); }
@Test public void shouldBuildResultFromCheckoutResponse() throws Exception { String responseBody = "{\"status\":\"failure\",messages=[\"message-one\",\"message-two\"]}"; Result result = messageHandler.responseMessageForCheckout(responseBody); assertFailureResult(result, List.of("message-one...
T getFunction(final List<SqlArgument> arguments) { // first try to get the candidates without any implicit casting Optional<T> candidate = findMatchingCandidate(arguments, false); if (candidate.isPresent()) { return candidate.get(); } else if (!supportsImplicitCasts) { throw createNoMatchin...
@Test public void shouldChooseLaterVariadicWhenTwoObjVariadicsMatch() { // Given: givenFunctions( function(OTHER, 1, GenericType.of("A"), OBJ_VARARGS, STRING, DOUBLE), function(EXPECTED, 2, GenericType.of("B"), INT, OBJ_VARARGS, DOUBLE) ); // When: final KsqlScalarFunction...
public <E extends SamplingEntry> Iterable<E> getRandomSamples(int sampleCount) { if (sampleCount < 0) { throw new IllegalArgumentException("Sample count cannot be a negative value."); } if (sampleCount == 0 || size() == 0) { return Collections.emptyList(); } ...
@Test public void test_getRandomSamples_whenSampleCountIsGreaterThenCapacity() { final int entryCount = 10; final int sampleCount = 100; map = new SampleableConcurrentHashMap<>(entryCount); // put single entry map.put(1, 1); Iterable<SampleableConcurrentHashMap.Sam...
boolean valid(int nodeId, MetadataImage image) { TopicImage topicImage = image.topics().getTopic(topicIdPartition.topicId()); if (topicImage == null) { return false; // The topic has been deleted. } PartitionRegistration partition = topicImage.partitions().get(topicIdPartitio...
@Test public void testAssignmentReplicaNotOnBrokerIsNotValid() { assertFalse(new Assignment( new TopicIdPartition(Uuid.fromString("rTudty6ITOCcO_ldVyzZYg"), 0), Uuid.fromString("rzRT8XZaSbKsP6j238zogg"), 0, NoOpRunnable.INSTANCE).valid(3, TEST_IMAGE)); }
public <T> List<T> fromList(final String json, final Class<T> clazz) { return GSON.fromJson(json, TypeToken.getParameterized(List.class, clazz).getType()); }
@Test public void testFromList() { List<String> testList = ImmutableList.of("123", "test", "测试"); String testJson = "[\"123\",\"test\",\"测试\"]"; assertEquals(testList, GsonUtils.getInstance().fromList(testJson, String.class)); }
public static Ip4Prefix valueOf(int address, int prefixLength) { return new Ip4Prefix(Ip4Address.valueOf(address), prefixLength); }
@Test(expected = IllegalArgumentException.class) public void testInvalidValueOfStringTooLongPrefixLengthIPv4() { Ip4Prefix ipPrefix; ipPrefix = Ip4Prefix.valueOf("1.2.3.4/33"); }
public static Result label(long durationInMillis) { double nbSeconds = durationInMillis / 1000.0; double nbMinutes = nbSeconds / 60; double nbHours = nbMinutes / 60; double nbDays = nbHours / 24; double nbYears = nbDays / 365; return getMessage(nbSeconds, nbMinutes, nbHours, nbDays, nbYears); ...
@Test public void year_ago() { DurationLabel.Result result = DurationLabel.label(now() - ago(14 * MONTH)); assertThat(result.key()).isEqualTo("duration.year"); assertThat(result.value()).isNull(); }
@Override public void showPreviewForKey( Keyboard.Key key, Drawable icon, View parentView, PreviewPopupTheme previewPopupTheme) { KeyPreview popup = getPopupForKey(key, parentView, previewPopupTheme); Point previewPosition = mPositionCalculator.calculatePositionForPreview( key, previ...
@Test public void testReuseForTheSameKey() { KeyPreviewsManager underTest = new KeyPreviewsManager(getApplicationContext(), mPositionCalculator, 3); underTest.showPreviewForKey(mTestKeys[0], "y", mKeyboardView, mTheme); final PopupWindow firstPopupWindow = getLatestCreatedPopupWindow(); Asser...
@Override public CompletableFuture<Void> closeAsync() { synchronized (lock) { if (isShutdown) { return terminationFuture; } else { isShutdown = true; final Collection<CompletableFuture<Void>> terminationFutures = new ArrayList<>(3); ...
@Test void testReporterScheduling() throws Exception { MetricConfig config = new MetricConfig(); config.setProperty("arg1", "hello"); config.setProperty(MetricOptions.REPORTER_INTERVAL.key(), "50 MILLISECONDS"); final ReportCountingReporter reporter = new ReportCountingReporter(); ...
@Override public ExecuteResult execute(final ServiceContext serviceContext, final ConfiguredKsqlPlan plan, final boolean restoreInProgress) { try { final ExecuteResult result = EngineExecutor .create(primaryContext, serviceContext, plan.getConfig()) .execut...
@Test public void shouldNotShowHintWhenFailingToDropNonExistingStream() { // Given: setupKsqlEngineWithSharedRuntimeEnabled(); KsqlEngineTestUtil.execute( serviceContext, ksqlEngine, "create table \"bar\" as select * from test2;", ksqlConfig, Collections.emptyMap() ...
public final HttpClient doOnError(BiConsumer<? super HttpClientRequest, ? super Throwable> doOnRequestError, BiConsumer<? super HttpClientResponse, ? super Throwable> doOnResponseError) { Objects.requireNonNull(doOnRequestError, "doOnRequestError"); Objects.requireNonNull(doOnResponseError, "doOnResponseError");...
@Test void doOnError() { disposableServer = createServer() .handle((req, resp) -> { if (req.requestHeaders().contains("during")) { return resp.sendString(Flux.just("test").hide()) .then(Mono.error(new RuntimeException("test"))...
public String asString(Map<String, ValueReference> parameters) { switch (valueType()) { case STRING: return String.class.cast(value()); case PARAMETER: return asType(parameters, String.class); default: throw new IllegalStateExce...
@Test public void asString() { assertThat(ValueReference.of("Test").asString(Collections.emptyMap())).isEqualTo("Test"); assertThatThrownBy(() -> ValueReference.of(false).asString(Collections.emptyMap())) .isInstanceOf(IllegalStateException.class) .hasMessage("Expecte...
public List<Supplier<PageProjectionWithOutputs>> compileProjections( SqlFunctionProperties sqlFunctionProperties, Map<SqlFunctionId, SqlInvokedFunction> sessionFunctions, List<? extends RowExpression> projections, boolean isOptimizeCommonSubExpression, Optiona...
@Test public void testCommonSubExpressionInProjection() { PageFunctionCompiler functionCompiler = new PageFunctionCompiler(createTestMetadataManager(), 0); List<Supplier<PageProjectionWithOutputs>> pageProjectionsCSE = functionCompiler.compileProjections(SESSION.getSqlFunctionProperties(), Immu...
static int run(File buildResult, Path root) throws IOException { // parse included dependencies from build output final Map<String, Set<Dependency>> modulesWithBundledDependencies = combineAndFilterFlinkDependencies( ShadeParser.parseShadeOutput(buildResult.toPath...
@Test void testRunRejectsIncorrectNotice() throws IOException { final String moduleName = "test"; final Dependency bundledDependency = Dependency.create("a", "b", "c", null); final Map<String, Set<Dependency>> bundleDependencies = new HashMap<>(); bundleDependencies.put(moduleName, C...
@Override public InetAddress address(String inetHost, ResolvedAddressTypes resolvedAddressTypes) { return firstAddress(addresses(inetHost, resolvedAddressTypes)); }
@Test public void shouldPickIpv6WhenBothAreDefinedButIpv6IsPreferred() { HostsFileEntriesProvider.Parser parser = givenHostsParserWith( LOCALHOST_V4_ADDRESSES, LOCALHOST_V6_ADDRESSES ); DefaultHostsFileEntriesResolver resolver = new DefaultHostsFileEntriesRes...
public static Sensor getInvocationSensor( final Metrics metrics, final String sensorName, final String groupName, final String functionDescription ) { final Sensor sensor = metrics.sensor(sensorName); if (sensor.hasMetrics()) { return sensor; } final BiFunction<String, S...
@Test public void shouldGetSensorWithCorrectName() { // When: FunctionMetrics .getInvocationSensor(metrics, SENSOR_NAME, GROUP_NAME, FUNC_NAME); // Then: verify(metrics).sensor(SENSOR_NAME); }
@SuppressWarnings("unused") // Required for automatic type inference public static <K> Builder0<K> forClass(final Class<K> type) { return new Builder0<>(); }
@Test(expected = IllegalArgumentException.class) public void shouldThrowOnDuplicateKey0() { HandlerMaps.forClass(BaseType.class) .put(LeafTypeA.class, handler0_1) .put(LeafTypeA.class, handler0_2); }
@Override public int compareTo(Block leftBlock, int leftPosition, Block rightBlock, int rightPosition) { long leftLow = leftBlock.getLong(leftPosition, 0); long leftHigh = leftBlock.getLong(leftPosition, SIZE_OF_LONG); long rightLow = rightBlock.getLong(rightPosition, 0); long ri...
@Test public void testCompareTo() { testCompare("0", "-1234567891.1234567890", 1); testCompare("1234567890.1234567890", "1234567890.1234567890", 0); testCompare("1234567890.1234567890", "1234567890.1234567891", -1); testCompare("1234567890.1234567890", "1234567890.1234567889", 1)...
@Override public List<SocialUserDO> getSocialUserList(Long userId, Integer userType) { // 获得绑定 List<SocialUserBindDO> socialUserBinds = socialUserBindMapper.selectListByUserIdAndUserType(userId, userType); if (CollUtil.isEmpty(socialUserBinds)) { return Collections.emptyList(); ...
@Test public void testGetSocialUserList() { Long userId = 1L; Integer userType = UserTypeEnum.ADMIN.getValue(); // mock 获得社交用户 SocialUserDO socialUser = randomPojo(SocialUserDO.class).setType(SocialTypeEnum.GITEE.getType()); socialUserMapper.insert(socialUser); // 可被查到 ...
@Override public OpenstackNode node(String hostname) { return osNodeStore.node(hostname); }
@Test public void testGetNodeByHostname() { assertTrue(ERR_NOT_FOUND, Objects.equals( target.node(COMPUTE_2_HOSTNAME), COMPUTE_2)); assertTrue(ERR_NOT_FOUND, Objects.equals( target.node(COMPUTE_3_HOSTNAME), COMPUTE_3)); assertTrue(ERR_NOT_FOUND, Objects.equals...
@VisibleForTesting boolean hasNoActiveWindows() { return activeWindows.getActiveAndNewWindows().isEmpty(); }
@Test public void testMergingWithReusedWindow() throws Exception { Duration allowedLateness = Duration.millis(50); ReduceFnTester<Integer, Iterable<Integer>, IntervalWindow> tester = ReduceFnTester.nonCombining( Sessions.withGapDuration(Duration.millis(10)), mockTriggerStateMac...
public KafkaMetadataState computeNextMetadataState(KafkaStatus kafkaStatus) { KafkaMetadataState currentState = metadataState; metadataState = switch (currentState) { case KRaft -> onKRaft(kafkaStatus); case ZooKeeper -> onZooKeeper(kafkaStatus); case KRaftMigration -...
@Test public void testFromKRaftDualWritingToZookeeper() { Kafka kafka = new KafkaBuilder(KAFKA) .editMetadata() .addToAnnotations(Annotations.ANNO_STRIMZI_IO_KRAFT, "disabled") .endMetadata() .withNewStatus() .withKafkaM...
@Override public void customize(ServiceInstance serviceInstance, ApplicationModel applicationModel) { Map<String, String> metadata = serviceInstance.getMetadata(); String propertyName = resolveMetadataPropertyName(serviceInstance); String propertyValue = resolveMetadataPropertyValue(applic...
@Test void test() { DubboBootstrap providerBootstrap = DubboBootstrap.newInstance(); ServiceConfig<DemoService> serviceConfig = new ServiceConfig<>(); serviceConfig.setInterface(DemoService.class); serviceConfig.setRef(new DemoServiceImpl()); serviceConfig.setDelay(1000); ...
@Override public TbPair<Boolean, JsonNode> upgrade(int fromVersion, JsonNode oldConfiguration) throws TbNodeException { if (fromVersion == 0) { var newConfigObjectNode = (ObjectNode) oldConfiguration; var directionPropertyName = "direction"; if (!newConfigObjectNode.has(d...
@Test void givenOldConfig_whenUpgrade_thenShouldReturnTrueResultWithNewConfig() throws Exception { // GIVEN var config = new TbCheckRelationNodeConfiguration().defaultConfiguration(); config.setEntityType(ORIGINATOR_ID.getEntityType().name()); config.setEntityId(ORIGINATOR_ID.getId()...
public static MqttMessage newMessage(MqttFixedHeader mqttFixedHeader, Object variableHeader, Object payload) { switch (mqttFixedHeader.messageType()) { case CONNECT : return new MqttConnectMessage( mqttFixedHeader, (MqttConnectVariableH...
@Test public void createSubscribeV5() { MqttFixedHeader fixedHeader = new MqttFixedHeader(MqttMessageType.SUBSCRIBE, false, AT_LEAST_ONCE, false, 0); MqttProperties properties = new MqttProperties(); properties.add(new MqttProperties.UserProperty("correlationId", "111222")); MqttMes...
@Activate public void activate() { eventHandler = newSingleThreadExecutor(groupedThreads("onos/security/store", "event-handler", log)); states = storageService.<ApplicationId, SecurityInfo>consistentMapBuilder() .withName("smonos-sdata") .withSerializer(STATE_SERIALIZ...
@Test public void testActivate() { eventHandler = newSingleThreadExecutor(groupedThreads("onos/security/store", "event-handler", log)); assertNotNull(eventHandler); }