focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override public PageResult<FileDO> getFilePage(FilePageReqVO pageReqVO) { return fileMapper.selectPage(pageReqVO); }
@Test public void testGetFilePage() { // mock 数据 FileDO dbFile = randomPojo(FileDO.class, o -> { // 等会查询到 o.setPath("yunai"); o.setType("image/jpg"); o.setCreateTime(buildTime(2021, 1, 15)); }); fileMapper.insert(dbFile); // 测试 path 不匹配 ...
@Override public Result invoke(Invocation invocation) throws RpcException { Result result; String value = getUrl().getMethodParameter( RpcUtils.getMethodName(invocation), MOCK_KEY, Boolean.FALSE.toString()) .trim(); if (ConfigUtils.isEmpty(value)) { ...
@Test void testMockInvokerFromOverride_Invoke_Fock_WithForceDefault() { URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.class.getName()) .addParameter( REFER_KEY, URL.encode(PATH_KEY + "=" + IHelloService.class.getName() ...
public static AuditActor user(@Nonnull String username) { if (isNullOrEmpty(username)) { throw new IllegalArgumentException("username must not be null or empty"); } return new AutoValue_AuditActor(URN_GRAYLOG_USER + username); }
@Test(expected = IllegalArgumentException.class) public void testNullUser() { AuditActor.user(null); }
public static String toJson(MetadataUpdate metadataUpdate) { return toJson(metadataUpdate, false); }
@Test public void testSetCurrentSchemaToJson() { String action = MetadataUpdateParser.SET_CURRENT_SCHEMA; int schemaId = 6; String expected = String.format("{\"action\":\"%s\",\"schema-id\":%d}", action, schemaId); MetadataUpdate update = new MetadataUpdate.SetCurrentSchema(schemaId); String actua...
public InnerCNode getTree() throws CodegenRuntimeException { try { if (root == null) parse(); } catch (DefParserException | IOException e) { throw new CodegenRuntimeException("Error parsing or reading config definition." + e.getMessage(), e); } return root; }
@Test void testTraverseTree() throws IOException { File defFile = new File(DEF_NAME); CNode root = new DefParser("test", new FileReader(defFile)).getTree(); assertNotNull(root); CNode[] children = root.getChildren(); assertEquals(38, children.length); int numGrandChi...
@Override protected CompletableFuture<LogListInfo> handleRequest( @Nonnull HandlerRequest<EmptyRequestBody> request, @Nonnull RestfulGateway gateway) throws RestHandlerException { if (logDir == null) { return CompletableFuture.completedFuture(new LogListInfo(Collections.e...
@Test void testGetJobManagerLogsList() throws Exception { File logRoot = temporaryFolder.toFile(); List<LogInfo> expectedLogInfo = Arrays.asList( new LogInfo("jobmanager.log", 5, 1632844800000L), new LogInfo("jobmanager.out", 7, 1632844...
public Resource getUsedResource() { return usedResource; }
@Test(timeout = 60000) public void testFifoScheduling() throws Exception { GenericTestUtils.setRootLogLevel(Level.DEBUG); MockRM rm = new MockRM(conf); rm.start(); MockNM nm1 = rm.registerNode("127.0.0.1:1234", 6 * GB); MockNM nm2 = rm.registerNode("127.0.0.2:5678", 4 * GB); RMApp app1 = Mock...
@ExecuteOn(TaskExecutors.IO) @Get(uri = "/maxTaskRunSetting") @Hidden public Integer maxTaskRunSetting() { return executionRepository.maxTaskRunSetting(); }
@Test void maxTaskRunSetting() { HttpClientResponseException e = assertThrows( HttpClientResponseException.class, () -> client.toBlocking().retrieve(HttpRequest.GET("/api/v1/taskruns/maxTaskRunSetting")) ); assertThat(e.getStatus(), is(HttpStatus.NOT_FOUND)); }
protected Permission toPermission(final Node node) { final Permission permission = new Permission(); if(node.getPermissions() != null) { switch(node.getType()) { case FOLDER: case ROOM: if(node.getPermissions().isCreate() ...
@Test public void testPermissionsFolder() throws Exception { final SDSAttributesAdapter f = new SDSAttributesAdapter(session); final Node node = new Node(); node.setIsEncrypted(false); node.setType(Node.TypeEnum.FOLDER); final NodePermissions permissions = new NodePermissions...
public Statement buildStatement(final ParserRuleContext parseTree) { return build(Optional.of(getSources(parseTree)), parseTree); }
@Test public void shouldDefaultToEmptyRefinementForBareQueries() { // Given: final SingleStatementContext stmt = givenQuery("SELECT * FROM TEST1;"); // When: final Query result = (Query) builder.buildStatement(stmt); // Then: assertThat("Should be pull", result.isPullQuery(), is(true...
public boolean hasViewAccessToTemplate(PipelineTemplateConfig template, CaseInsensitiveString username, List<Role> roles, boolean isGroupAdministrator) { boolean hasViewAccessToTemplate = template.getAuthorization().isViewUser(username, roles); hasViewAccessToTemplate = hasViewAccessToTemplate || (templ...
@Test public void shouldReturnFalseIfUserCannotViewTemplate() { CaseInsensitiveString templateViewUser = new CaseInsensitiveString("view"); String templateName = "template"; PipelineTemplateConfig template = PipelineTemplateConfigMother.createTemplate(templateName, StageConfigMother.manualSt...
@JsonIgnore public Set<Long> getSkippedIterationsWithCheckpoint() { Set<Long> skipList = new HashSet<>(); if (restartInfo != null) { skipList.addAll(restartInfo); } if (details != null) { details.flatten(WorkflowInstance.Status::isTerminal).entrySet().stream() .flatMap(e -> e.get...
@Test public void testGetSkippedIterationsWithCheckpoint() throws Exception { ForeachStepOverview overview = loadObject( "fixtures/instances/sample-foreach-step-overview.json", ForeachStepOverview.class); assertTrue(overview.getSkippedIterationsWithCheckpoint().isEmpty()); overview.se...
@VisibleForTesting static String logicalToProtoSchema(final LogicalSchema schema) { final ConnectSchema connectSchema = ConnectSchemas.columnsToConnectSchema(schema.columns()); final ProtobufSchema protobufSchema = new ProtobufData( new ProtobufDataConfig(ImmutableMap.of())).fromConnectSchema(con...
@Test public void shouldConvertLogicalSchemaToProtobufSchema() { // Given: final String expectedProtoSchemaString = "syntax = \"proto3\";\n" + "\n" + "message ConnectDefault1 {\n" + " int32 A = 1;\n" + " double B = 2;\n" + " repeated string C = 3;...
@POST @Path("/{connector}/restart") @Operation(summary = "Restart the specified connector") public Response restartConnector(final @PathParam("connector") String connector, final @Context HttpHeaders headers, final @DefaultValue("false") @Que...
@Test public void testRestartConnectorNotFound() { final ArgumentCaptor<Callback<Void>> cb = ArgumentCaptor.forClass(Callback.class); expectAndCallbackException(cb, new NotFoundException("not found")) .when(herder).restartConnector(eq(CONNECTOR_NAME), cb.capture()); assertThrows...
@Override public Serde<GenericKey> create( final FormatInfo format, final PersistenceSchema schema, final KsqlConfig ksqlConfig, final Supplier<SchemaRegistryClient> schemaRegistryClientFactory, final String loggerNamePrefix, final ProcessingLogContext processingLogContext, f...
@Test public void shouldNotThrowOnMultipleKeyColumns() { // Given: schema = PersistenceSchema.from( ImmutableList.of(column(SqlTypes.STRING), column(SqlTypes.INTEGER)), SerdeFeatures.of() ); // When: factory.create(format, schema, config, srClientFactory, LOGGER_PREFIX, processing...
@Operation(summary = "秒杀场景一(sychronized同步锁实现)") @PostMapping("/sychronized") public Result doWithSychronized(@RequestBody @Valid SeckillWebMockRequestDTO dto) { processSeckill(dto, SYCHRONIZED); return Result.ok(); //待mq监听器处理完成打印日志,不在此处打印日志 }
@Test void testDoWithSychronized() { SeckillWebMockRequestDTO requestDTO = new SeckillWebMockRequestDTO(); requestDTO.setSeckillId(1L); requestDTO.setRequestCount(1); requestDTO.setCorePoolSize(1); requestDTO.setMaxPoolSize(10); SeckillMockRequestDTO any = new Seckill...
@Override public ColumnStatistic getColumnStatistic(Table table, String column) { Preconditions.checkState(table != null); // get Statistics Table column info, just return default column statistics if (StatisticUtils.statisticTableBlackListCheck(table.getId())) { return ColumnSt...
@Test public void testLoadCacheLoadEmpty(@Mocked CachedStatisticStorage cachedStatisticStorage) { Database db = connectContext.getGlobalStateMgr().getDb("test"); Table table = db.getTable("t0"); new Expectations() { { cachedStatisticStorage.getColumnStatistic(tab...
@Nullable public RouterFunction<ServerResponse> create(ReverseProxy reverseProxy, String pluginName) { return createReverseProxyRouterFunction(reverseProxy, nullSafePluginName(pluginName)); }
@Test void shouldReturnNotFoundIfResourceNotFound() throws FileNotFoundException { var routerFunction = factory.create(mockReverseProxy(), "fakeA"); assertNotNull(routerFunction); var webClient = WebTestClient.bindToRouterFunction(routerFunction).build(); var pluginWrapper = Mockito...
public static <T> RetryTransformer<T> of(Retry retry) { return new RetryTransformer<>(retry); }
@Test public void shouldNotRetryWhenItThrowErrorSingle() { RetryConfig config = retryConfig(); Retry retry = Retry.of("testName", config); given(helloWorldService.returnHelloWorld()) .willThrow(new Error("BAM!")); Single.fromCallable(helloWorldService::returnHelloWorld) ...
public WatsonxAiRequest request(Prompt prompt) { WatsonxAiChatOptions options = WatsonxAiChatOptions.builder().build(); if (this.defaultOptions != null) { options = ModelOptionsUtils.merge(options, this.defaultOptions, WatsonxAiChatOptions.class); } if (prompt.getOptions() != null) { if (prompt.getOpti...
@Test public void testCreateRequestSuccessfullyWithDefaultParams() { String msg = "Test message"; WatsonxAiChatOptions modelOptions = WatsonxAiChatOptions.builder() .withModel("meta-llama/llama-2-70b-chat") .build(); Prompt prompt = new Prompt(msg, modelOptions); WatsonxAiRequest request = chatModel.r...
@Override public void handleGlobalFailure( Throwable cause, CompletableFuture<Map<String, String>> failureLabels) { context.goToFinished(context.getArchivedExecutionGraph(JobStatus.FAILED, cause)); }
@Test void testTransitionToFinishedOnGlobalFailure() { TestingStateWithoutExecutionGraph state = new TestingStateWithoutExecutionGraph(ctx, LOG); RuntimeException expectedException = new RuntimeException("This is a test exception"); ctx.setExpectFinished( archivedExecutionGr...
@Override public <T> T convert(DataTable dataTable, Type type) { return convert(dataTable, type, false); }
@Test void convert_to_map_of_primitive_to_map_of_primitive_to_object() { DataTable table = parse("", " | | 1 | 2 | 3 |", " | A | ♘ | | ♝ |", " | B | | | |", " | C | | ♝ | |"); registry.defineDataTableType(new DataTableType(Piece.clas...
@Override public synchronized void start() { LOG.info("Starting {}", this.getClass().getSimpleName()); Preconditions.checkState(mJvmPauseMonitor == null, "JVM pause monitor must not already exist"); mJvmPauseMonitor = new JvmPauseMonitor( Configuration.getMs(PropertyKey.JVM_MONITOR_SLEEP_INTERVAL_...
@Test public void doubleStart() { Configuration.set(PropertyKey.MASTER_JVM_MONITOR_ENABLED, true); SimpleService service = JvmMonitorService.Factory.create(); Assert.assertTrue(service instanceof JvmMonitorService); service.start(); Assert.assertThrows("JVM pause monitor must not already exist", ...
@Override public String getValue(EvaluationContext context) { // Use variable name if we just provide this. if (variableName != null && variable == null) { variable = context.lookupVariable(variableName); return (variable != null ? variable.toString() : ""); } String proper...
@Test void testXPathWithNamespaceValue() { String xmlString = "<ns:library xmlns:ns=\"https://microcks.io\">\n" + " <ns:name>My Personal Library</ns:name>\n" + " <ns:books>\n" + " <ns:book><ns:title>Title 1</ns:title><ns:author>Jane Doe</ns:author></ns:book>\n" + " <...
@GET @Path("status") @Produces({MediaType.APPLICATION_JSON}) public Map<String, String> status() { return STATUS_OK; }
@Test public void testStatus() { assertEquals(server.status().get("status"), "ok"); }
@Override public void exportData(JsonWriter writer) throws IOException { // version tag at the root writer.name(THIS_VERSION); writer.beginObject(); // clients list writer.name(CLIENTS); writer.beginArray(); writeClients(writer); writer.endArray(); writer.name(GRANTS); writer.beginArray(); wr...
@Test public void testExportAccessTokens() throws IOException, ParseException { String expiration1 = "2014-09-10T22:49:44.090+00:00"; Date expirationDate1 = formatter.parse(expiration1, Locale.ENGLISH); ClientDetailsEntity mockedClient1 = mock(ClientDetailsEntity.class); when(mockedClient1.getClientId()).then...
@Override public TreeModel<Regressor> train(Dataset<Regressor> examples, Map<String, Provenance> runProvenance) { return train(examples, runProvenance, INCREMENT_INVOCATION_COUNT); }
@Test public void testThreeDenseData() { Pair<Dataset<Regressor>,Dataset<Regressor>> p = RegressionDataGenerator.threeDimDenseTrainTest(1.0, false); TreeModel<Regressor> llModel = t.train(p.getA()); RegressionEvaluation llEval = e.evaluate(llModel,p.getB()); double expectedDim1 = -0....
public DebtRatingGrid getDebtRatingGrid() { return ratingGrid; }
@Test public void load_rating_grid() { settings.setProperty(CoreProperties.RATING_GRID, "1,3.4,8,50"); RatingSettings configurationLoader = new RatingSettings(settings.asConfig()); double[] grid = configurationLoader.getDebtRatingGrid().getGridValues(); assertThat(grid).hasSize(4); assertThat(gri...
@Override public <VO, VR> KStream<K, VR> join(final KStream<K, VO> otherStream, final ValueJoiner<? super V, ? super VO, ? extends VR> joiner, final JoinWindows windows) { return join(otherStream, toValueJoinerWithKey(joiner), w...
@Test public void shouldNotAllowNullJoinedOnTableJoin() { final NullPointerException exception = assertThrows( NullPointerException.class, () -> testStream.join(testTable, MockValueJoiner.TOSTRING_JOINER, null)); assertThat(exception.getMessage(), equalTo("joined can't be nul...
public static String toString(RedisCommand<?> command, Object... params) { if (RedisCommands.AUTH.equals(command)) { return "command: " + command + ", params: (password masked)"; } return "command: " + command + ", params: " + LogHelper.toString(params); }
@Test public void toStringWithNull() { assertThat(LogHelper.toString(null)).isEqualTo("null"); }
@Override public Token login(LoginRequest loginRequest) { final UserEntity userEntityFromDB = userRepository .findUserEntityByEmail(loginRequest.getEmail()) .orElseThrow( () -> new UserNotFoundException("Can't find with given email: " ...
@Test void login_ValidCredentials_ReturnsToken() { // Given LoginRequest loginRequest = LoginRequest.builder() .email("test@example.com") .password("password123") .build(); UserEntity userEntity = new UserEntityBuilder().withValidUserFields()...
public static Getter newMethodGetter(Object object, Getter parent, Method method, String modifier) throws Exception { return newGetter(object, parent, modifier, method.getReturnType(), method::invoke, (t, et) -> new MethodGetter(parent, method, modifier, t, et)); }
@Test public void newMethodGetter_whenExtractingFromNonEmpty_Array_nullFirst_FieldAndParentIsNonEmptyMultiResult_thenInferReturnType() throws Exception { OuterObject object = new OuterObject("name", null, new InnerObject("inner", 0, 1, 2, 3)); Getter parentGetter = GetterFactory.newMeth...
public static CompositeData parseComposite(URI uri) throws URISyntaxException { CompositeData rc = new CompositeData(); rc.scheme = uri.getScheme(); String ssp = stripPrefix(uri.getRawSchemeSpecificPart().trim(), "//").trim(); parseComposite(uri, rc, ssp); rc.fragment = uri.ge...
@Test public void testEmptyCompositeWithParenthesisInParam() throws Exception { URI uri = new URI("failover://()?updateURIsURL=file:/C:/Dir(1)/a.csv"); CompositeData data = URISupport.parseComposite(uri); assertEquals(0, data.getComponents().length); assertEquals(1, data.getParameter...
public String getPackageName() { return this.context != null ? this.context.getPackageName() : ""; }
@Test public void getPackageName() { assertThat(contextUtil.getPackageName(), is("com.github.tony19.logback.android.test")); }
@Override public Path touch(final Path file, final TransferStatus status) throws BackgroundException { try { final IRODSFileSystemAO fs = session.getClient(); final int descriptor = fs.createFile(file.getAbsolute(), DataObjInp.OpenFlags.WRITE_TRUNCATE, DataObjInp.DEFA...
@Test public void testTouch() throws Exception { final ProtocolFactory factory = new ProtocolFactory(new HashSet<>(Collections.singleton(new IRODSProtocol()))); final Profile profile = new ProfilePlistReader(factory).read( this.getClass().getResourceAsStream("/iRODS (iPlant Collabora...
public void update(String attemptId, boolean isRetry, String topic, String group, int queueId, long popTime, long invisibleTime, List<Long> msgQueueOffsetList, StringBuilder orderInfoBuilder) { String key = buildKey(topic, group); ConcurrentHashMap<Integer/*queueId*/, OrderInfo> qs = table.get(k...
@Test public void testConsumedCountForMultiQueue() { { // consume two new messages StringBuilder orderInfoBuilder = new StringBuilder(); consumerOrderInfoManager.update( null, false, TOPIC, GROUP, ...
public String build() { if (columnDefs.isEmpty()) { throw new IllegalStateException("No column has been defined"); } StringBuilder sql = new StringBuilder().append("ALTER TABLE ").append(tableName).append(" "); switch (dialect.getId()) { case PostgreSql.ID: addColumns(sql, "ADD COLU...
@Test public void add_columns_on_postgresql() { assertThat(createSampleBuilder(new PostgreSql()).build()) .isEqualTo("ALTER TABLE issues ADD COLUMN date_in_ms BIGINT NULL, ADD COLUMN name VARCHAR (10) NOT NULL, ADD COLUMN col_with_default BOOLEAN DEFAULT false NOT NULL, ADD COLUMN varchar_col_with_default V...
public static String formatBetween(Date beginDate, Date endDate, BetweenFormatter.Level level) { return formatBetween(between(beginDate, endDate, DateUnit.MS), level); }
@Test public void formatBetweenTest() { final String dateStr1 = "2017-03-01 22:34:23"; final Date date1 = DateUtil.parse(dateStr1); final String dateStr2 = "2017-04-01 23:56:14"; final Date date2 = DateUtil.parse(dateStr2); final long between = DateUtil.between(date1, date2, DateUnit.MS); final String fo...
@Override public Object cloneValueData( Object object ) throws KettleValueException { Timestamp timestamp = getTimestamp( object ); if ( timestamp == null ) { return null; } Timestamp clone = new Timestamp( timestamp.getTime() ); clone.setNanos( timestamp.getNanos() ); return clone; }
@Test public void testCloneValueData() throws KettleValueException { ValueMetaTimestamp valueMetaTimestamp = new ValueMetaTimestamp(); Object clonedTimestamp = valueMetaTimestamp.cloneValueData( TIMESTAMP_WITH_NANOSECONDS ); assertEquals( TIMESTAMP_WITH_NANOSECONDS, clonedTimestamp ); }
@ConstantFunction(name = "int_divide", argTypes = {TINYINT, TINYINT}, returnType = TINYINT) public static ConstantOperator intDivideTinyInt(ConstantOperator first, ConstantOperator second) { return ConstantOperator.createTinyInt((byte) (first.getTinyInt() / second.getTinyInt())); }
@Test public void intDivideTinyInt() { assertEquals(1, ScalarOperatorFunctions.intDivideTinyInt(O_TI_10, O_TI_10).getTinyInt()); }
public void sendRequests(Callback<None> callback) { LOG.info("Event Bus Requests throttler started for {} keys at a {} load rate", _keysToFetch.size(), _maxConcurrentRequests); if (_keysToFetch.size() == 0) { callback.onSuccess(None.none()); return; } _callback = callback; ma...
@Test(timeOut = 10000) public void testThrottlingUnlimitedRequests() throws InterruptedException, ExecutionException, TimeoutException { TestSubscriber testSubscriber = new TestSubscriber(); TestEventBus testZkEventBus = new TestEventBus(testSubscriber, 50); final int nRequests = 100; int concurre...
public List<GroupedDataRecord> group(final List<DataRecord> dataRecords) { List<GroupedDataRecord> result = new ArrayList<>(100); List<DataRecord> mergedDataRecords = dataRecords.get(0).getUniqueKeyValue().isEmpty() ? dataRecords : merge(dataRecords); Map<String, List<DataRecord>> tableGroup = m...
@Test void assertGroup() { List<DataRecord> dataRecords = mockDataRecords(); List<GroupedDataRecord> groupedDataRecords = groupEngine.group(dataRecords); assertThat(groupedDataRecords.size(), is(2)); assertThat(groupedDataRecords.get(0).getTableName(), is("t1")); assertThat(g...
@Override public Path mkdir(final Path folder, final TransferStatus status) throws BackgroundException { try { final IRODSFileSystemAO fs = session.getClient(); final IRODSFile f = fs.getIRODSFileFactory().instanceIRODSFile(folder.getAbsolute()); fs.mkdir(f, false); ...
@Test public void testMakeDirectory() throws Exception { final ProtocolFactory factory = new ProtocolFactory(new HashSet<>(Collections.singleton(new IRODSProtocol()))); final Profile profile = new ProfilePlistReader(factory).read( this.getClass().getResourceAsStream("/iRODS (iPlant C...
public Map<String, String> pukRequestAllowed(PukRequest request) throws PukRequestException { final PenRequestStatus result = repository.findFirstByBsnAndDocTypeAndSequenceNoOrderByRequestDatetimeDesc(request.getBsn(), request.getDocType(), request.getSequenceNo()); checkExpirationDatePen(result); ...
@Test public void pukRequestAllowedIsNotAllowedAfter22Days() throws PukRequestException { status.setPinResetValidDate(LocalDateTime.of(2019, 1, 1, 12, 34)); Exception exception = assertThrows(PukRequestException.class, () -> { service.pukRequestAllowed(request); }); asse...
public static String addUserHomeDirectoryIfApplicable(String origPathStr, String user) throws IOException, URISyntaxException { if(origPathStr == null || origPathStr.isEmpty()) { return "/user/" + user; } Path p = new Path(origPathStr); if(p.isAbsolute()) { return origPathStr; } ...
@Test public void testConstructingUserHomeDirectory() throws Exception { String[] sources = new String[] { "output+", "/user/hadoop/output", "hdfs://container", "hdfs://container/", "hdfs://container/path", "output#link", "hdfs://cointaner/output#link", "hdfs://container@acc/test", "/user/webhca...
@VisibleForTesting static Map<String, AtomicInteger> getUnknownTablesWarningsMap() { return unknownTablesWarnings; }
@Test public void unknownTableOrdering() throws Exception { SpannerSchema.Builder builder = SpannerSchema.builder(); builder.addColumn("test1", "key", "INT64"); builder.addKeyPart("test1", "key", false); SpannerSchema schema = builder.build(); // Verify that the encoded keys are ordered by tabl...
public int nodeId() { return nodeId; }
@Test public void testNoOpRecordWriteAfterTimeout() throws Throwable { long maxIdleIntervalNs = 1_000; long maxReplicationDelayMs = 60_000; try ( LocalLogManagerTestEnv logEnv = new LocalLogManagerTestEnv.Builder(3). build(); QuorumControllerTestEnv co...
public void deleteEtlOutputPath(String outputPath, BrokerDesc brokerDesc) { try { if (brokerDesc.hasBroker()) { BrokerUtil.deletePath(outputPath, brokerDesc); } else { HdfsUtil.deletePath(outputPath, brokerDesc); } LOG.info("delete ...
@Test public void testDeleteEtlOutputPath(@Mocked BrokerUtil brokerUtil) throws UserException { new Expectations() { { BrokerUtil.deletePath(etlOutputPath, (BrokerDesc) any); times = 1; } }; BrokerDesc brokerDesc = new BrokerDesc(broke...
@VisibleForTesting static Optional<String> findEntryClass(File jarFile) throws IOException { return findFirstManifestAttribute( jarFile, PackagedProgram.MANIFEST_ATTRIBUTE_ASSEMBLER_CLASS, PackagedProgram.MANIFEST_ATTRIBUTE_MAIN_CLASS); }
@Test void testFindEntryClassNoEntry() throws IOException { File jarFile = createJarFileWithManifest(ImmutableMap.of()); Optional<String> entry = JarManifestParser.findEntryClass(jarFile); assertThat(entry).isNotPresent(); }
public MetricSampleAggregationResult<String, PartitionEntity> aggregate(Cluster cluster, long now, OperationProgress operationProgress) throws NotEnoughValidWindowsEx...
@Test public void testAggregate() throws NotEnoughValidWindowsException { KafkaCruiseControlConfig config = new KafkaCruiseControlConfig(getLoadMonitorProperties()); Metadata metadata = getMetadata(Collections.singleton(TP)); KafkaPartitionMetricSampleAggregator metricSampleAggregator = new KafkaP...
int startReconfiguration(final String nodeType, final String address) throws IOException, InterruptedException { return startReconfigurationUtil(nodeType, address, System.out, System.err); }
@Test public void testAllDatanodesReconfig() throws IOException, InterruptedException, TimeoutException { ReconfigurationUtil reconfigurationUtil = mock(ReconfigurationUtil.class); cluster.getDataNodes().get(0).setReconfigurationUtil(reconfigurationUtil); cluster.getDataNodes().get(1).setReconfigura...
public void checkJavaVersion() { Runtime.Version version = Runtime.version(); if (version.compareTo(Runtime.Version.parse("17")) < 0) { LOG.warn(LOG_MESSAGE); String documentationLink = documentationLinkGenerator.getDocumentationLink("/analyzing-source-code/scanner-environment"); analysisWarni...
@Test public void given_runtime11_should_log_message() { try (MockedStatic<Runtime> utilities = Mockito.mockStatic(Runtime.class)) { Runtime.Version version = Runtime.Version.parse("11"); utilities.when(Runtime::version).thenReturn(version); underTest.checkJavaVersion(); assertThat(logTe...
public void terminateCluster(final List<String> deleteTopicPatterns) { terminatePersistentQueries(); deleteSinkTopics(deleteTopicPatterns); deleteTopics(managedTopics); ksqlEngine.close(); }
@Test public void shouldCleanUpSchemasForExplicitTopicListAvro() throws Exception { // Given: givenTopicsExistInKafka("K_Foo"); givenSinkTopicsExistInMetastore(FormatFactory.AVRO, "K_Foo"); givenSchemasForTopicsExistInSchemaRegistry("K_Foo"); // When: clusterTerminator.terminateCluster(Immuta...
public Print() { this("\n"); }
@Test public void testPrint() throws IOException { Print print = new Print(); PrintStream out = mock(PrintStream.class); FindOptions options = new FindOptions(); options.setOut(out); print.setOptions(options); String filename = "/one/two/test"; PathData item = new PathData(filename, mockF...
public static <T> Read<T> readAvrosWithBeamSchema(Class<T> clazz) { if (clazz.equals(GenericRecord.class)) { throw new IllegalArgumentException("For GenericRecord, please call readAvroGenericRecords"); } AvroCoder<T> coder = AvroCoder.of(clazz); org.apache.avro.Schema avroSchema = coder.getSchema(...
@Test public void testAvroPojo() { AvroCoder<GenericClass> coder = AvroCoder.of(GenericClass.class); List<GenericClass> inputs = Lists.newArrayList( new GenericClass( 1, "foo", new DateTime().withDate(2019, 10, 1).withZone(DateTimeZone.UTC)), new GenericClass( ...
@Override public RestResponse<KsqlEntityList> makeKsqlRequest( final URI serverEndPoint, final String sql, final Map<String, ?> requestProperties) { final KsqlTarget target = sharedClient .target(serverEndPoint); return getTarget(target) .postKsqlRequest(sql, requestProperti...
@Test public void shouldPostRequest() { // When: final RestResponse<KsqlEntityList> result = client.makeKsqlRequest(SERVER_ENDPOINT, "Sql", ImmutableMap.of()); // Then: verify(target).postKsqlRequest("Sql", ImmutableMap.of(), Optional.empty()); assertThat(result, is(response)); }
public static List<String> splitToWhiteSpaceSeparatedTokens(String input) { if (input == null) { return new ArrayList<>(); } StringTokenizer tokenizer = new StringTokenizer(input.trim(), QUOTE_CHAR + WHITESPACE, true); List<String> tokens = new ArrayList<>(); StringB...
@Test public void testDoubleQuote() { List<String> args = splitToWhiteSpaceSeparatedTokens("\"\"arg0\"\""); assertEquals("\"arg0\"", args.get(0)); }
public boolean isAfterFlink114() { return flinkInterpreter.getFlinkVersion().isAfterFlink114(); }
@Test void testBatchIPyFlink() throws InterpreterException, IOException { if (!flinkInnerInterpreter.getFlinkVersion().isAfterFlink114()) { testBatchPyFlink(interpreter, flinkScalaInterpreter); } }
public static String formatExpression(final Expression expression) { return formatExpression(expression, FormatOptions.of(s -> false)); }
@Test public void shouldFormatInListExpression() { assertThat(ExpressionFormatter.formatExpression(new InListExpression(Collections.singletonList(new StringLiteral("a")))), equalTo("('a')")); }
@CanIgnoreReturnValue public final Ordered containsExactlyEntriesIn(Multimap<?, ?> expectedMultimap) { checkNotNull(expectedMultimap, "expectedMultimap"); checkNotNull(actual); ListMultimap<?, ?> missing = difference(expectedMultimap, actual); ListMultimap<?, ?> extra = difference(actual, expectedMult...
@Test public void containsExactlyFailureMissing() { ImmutableMultimap<Integer, String> expected = ImmutableMultimap.of(3, "one", 3, "six", 3, "two", 4, "five", 4, "four"); ListMultimap<Integer, String> actual = LinkedListMultimap.create(expected); actual.remove(3, "six"); actual.remove(4, "fiv...
@Override public void execute() throws Exception { LOG.debug("Executing map task"); try (Closeable stateCloser = executionStateTracker.activate()) { try { // Start operations, in reverse-execution-order, so that a // consumer is started before a producer might output to it. // S...
@Test @SuppressWarnings("unchecked") /** * This test makes sure that any metrics reported within an operation are part of the metric * containers returned by {@link getMetricContainers}. */ public void testGetMetricContainers() throws Exception { ExecutionStateTracker stateTracker = new Dataf...
public String format() { return dataSourceName + DELIMITER + tableName; }
@Test void assertFormatIncludeInstance() { String expected = "ds_0.db_0.tbl_0"; DataNode dataNode = new DataNode(expected); assertThat(dataNode.format(), is(expected)); }
void publishLogDelta( MetadataDelta delta, MetadataImage newImage, LogDeltaManifest manifest ) { bytesSinceLastSnapshot += manifest.numBytes(); if (bytesSinceLastSnapshot >= maxBytesSinceLastSnapshot) { if (eventQueue.isEmpty()) { scheduleEmit("we ...
@Test public void testSnapshotsDisabled() throws Exception { MockFaultHandler faultHandler = new MockFaultHandler("SnapshotGenerator"); MockEmitter emitter = new MockEmitter().setReady(); AtomicReference<String> disabledReason = new AtomicReference<>(); try (SnapshotGenerator generat...
@Override protected CouchbaseEndpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception { CouchbaseEndpoint endpoint = new CouchbaseEndpoint(uri, remaining, this); setProperties(endpoint, parameters); return endpoint; }
@Test public void testCouchbaseNullAdditionalHosts() throws Exception { Map<String, Object> params = new HashMap<>(); params.put("additionalHosts", null); params.put("bucket", "bucket"); String uri = "couchbase:http://localhost"; String remaining = "http://localhost"; ...
@Override public void updateNode(K8sNode node) { checkNotNull(node, ERR_NULL_NODE); K8sNode intNode; K8sNode extNode; K8sNode localNode; K8sNode tunNode; K8sNode existingNode = nodeStore.node(node.hostname()); checkNotNull(existingNode, ERR_NULL_NODE); ...
@Test(expected = NullPointerException.class) public void testUpdateNotExistingNode() { target.updateNode(MINION_1); }
public static SessionBytesStoreSupplier persistentSessionStore(final String name, final Duration retentionPeriod) { Objects.requireNonNull(name, "name cannot be null"); final String msgPrefix = prepareMillisCheckFailMsgPrefix(retentionPe...
@Test public void shouldThrowIfIPersistentSessionStoreRetentionPeriodIsNegative() { final Exception e = assertThrows(IllegalArgumentException.class, () -> Stores.persistentSessionStore("anyName", ofMillis(-1))); assertEquals("retentionPeriod cannot be negative", e.getMessage()); }
@PostMapping("/syncData") @RequiresPermissions("system:authen:modify") public ShenyuAdminResult syncData() { return appAuthService.syncData(); }
@Test public void testSyncData() throws Exception { this.mockMvc.perform(MockMvcRequestBuilders.post("/appAuth/syncData")) .andExpect(status().isOk()) .andReturn(); }
@Override /** * Parses the given text to transform it to the desired target type. * @param text The LLM output in string format. * @return The parsed output in the desired target type. */ public T convert(@NonNull String text) { try { // Remove leading and trailing whitespace text = text.trim(); /...
@Test public void convertClassWithDateType() { var converter = new BeanOutputConverter<>(TestClassWithDateProperty.class); var testClass = converter.convert("{ \"someString\": \"2020-01-01\" }"); assertThat(testClass.getSomeString()).isEqualTo(LocalDate.of(2020, 1, 1)); }
public String readWPHexString(int numOfBytes) throws IOException { StringBuilder b = new StringBuilder(); for (int i = 0; i < numOfBytes; i++) { b.append(readWPHex()); } return b.toString(); }
@Test public void testReadHexString() throws Exception { try (WPInputStream wpInputStream = emptyWPStream()) { wpInputStream.readWPHexString(10); fail("should have thrown EOF"); } catch (EOFException e) { //swallow } }
@Override public BasicTypeDefine reconvert(Column column) { BasicTypeDefine.BasicTypeDefineBuilder builder = BasicTypeDefine.builder() .name(column.getName()) .nullable(column.isNullable()) .comment(column.getComment()) ...
@Test public void testReconvertDouble() { Column column = PhysicalColumn.builder().name("test").dataType(BasicType.DOUBLE_TYPE).build(); BasicTypeDefine typeDefine = SqlServerTypeConverter.INSTANCE.reconvert(column); Assertions.assertEquals(column.getName(), typeDefine.getNa...
public static String getJPushSDKName(byte whichPushSDK) { String name; switch (whichPushSDK) { case 0: name = "Jpush"; break; case 1: name = "Xiaomi"; break; case 2: name = "HUAWEI"; ...
@Test public void getJPushSDKName() { Assert.assertEquals("Jpush", PushUtils.getJPushSDKName((byte) 0)); Assert.assertEquals("Xiaomi", PushUtils.getJPushSDKName((byte) 1)); Assert.assertEquals("HUAWEI", PushUtils.getJPushSDKName((byte) 2)); Assert.assertEquals("Meizu", PushUtils.getJ...
public static <N> ImmutableGraph<N> singletonUndirectedGraph(N node) { final MutableGraph<N> graph = GraphBuilder.undirected().build(); graph.addNode(node); return ImmutableGraph.copyOf(graph); }
@Test public void singletonUndirectedGraph() { final ImmutableGraph<String> singletonGraph = Graphs.singletonUndirectedGraph("Test"); assertThat(singletonGraph.isDirected()).isFalse(); assertThat(singletonGraph.nodes()).containsExactly("Test"); assertThat(singletonGraph.edges()).isEm...
public String view(TableIdentifier ident) { return SLASH.join( "v1", prefix, "namespaces", RESTUtil.encodeNamespace(ident.namespace()), "views", RESTUtil.encodeString(ident.name())); }
@Test public void view() { TableIdentifier ident = TableIdentifier.of("ns", "view-name"); assertThat(withPrefix.view(ident)).isEqualTo("v1/ws/catalog/namespaces/ns/views/view-name"); assertThat(withoutPrefix.view(ident)).isEqualTo("v1/namespaces/ns/views/view-name"); }
@Override public void report(SortedMap<MetricName, Gauge> gauges, SortedMap<MetricName, Counter> counters, SortedMap<MetricName, Histogram> histograms, SortedMap<MetricName, Meter> meters, SortedMap<MetricName, Timer> timers...
@Test public void reportsHistogramValues() throws Exception { final Histogram histogram = mock(Histogram.class); when(histogram.getCount()).thenReturn(1L); final Snapshot snapshot = mock(Snapshot.class); when(snapshot.getMax()).thenReturn(2L); when(snapshot.getMean()).thenRe...
@Override public String getMethod() { return PATH; }
@Test public void testAnswerWebAppQueryWithEmptyId() { AnswerWebAppQuery answerWebAppQuery = AnswerWebAppQuery .builder() .webAppQueryId("") .queryResult(InlineQueryResultArticle .builder() .id("MyId") ...
@Override protected List<SegmentConversionResult> convert(PinotTaskConfig pinotTaskConfig, List<File> segmentDirs, File workingDir) throws Exception { int numInputSegments = segmentDirs.size(); _eventObserver.notifyProgress(pinotTaskConfig, "Converting segments: " + numInputSegments); String t...
@Test public void testConcat() throws Exception { FileUtils.deleteQuietly(WORKING_DIR); RealtimeToOfflineSegmentsTaskExecutor realtimeToOfflineSegmentsTaskExecutor = new RealtimeToOfflineSegmentsTaskExecutor(null, null); realtimeToOfflineSegmentsTaskExecutor.setMinionEventObserver(new Minio...
public static String toSanitizedString(Expression expr) { return ExpressionVisitors.visit(expr, new StringSanitizer()); }
@Test public void testSanitizeStringFallback() { Pattern filterPattern = Pattern.compile("^test = \\(hash-[0-9a-fA-F]{8}\\)$"); for (String filter : Lists.newArrayList( "2022-20-29", "2022-04-29T40:49:51.123456", "2022-04-29T23:70:51-07:00", "2022-04-29T...
public static Optional<ConnectorPageSource> createHivePageSource( Set<HiveRecordCursorProvider> cursorProviders, Set<HiveBatchPageSourceFactory> pageSourceFactories, Configuration configuration, ConnectorSession session, HiveFileSplit fileSplit, Op...
@Test public void testNotUseRecordReaderWithInputFormatAnnotationWithoutCustomSplit() { StorageFormat storageFormat = StorageFormat.create(ParquetHiveSerDe.class.getName(), HoodieParquetInputFormat.class.getName(), ""); Storage storage = new Storage(storageFormat, "test", Optional.empty(), true,...
@Override public void describe(SensorDescriptor descriptor) { descriptor .name("Xoo Highlighting Sensor") .onlyOnLanguages(Xoo.KEY); }
@Test public void testDescriptor() { sensor.describe(new DefaultSensorDescriptor()); }
@Override public double score(int[] truth, int[] prediction) { return of(truth, prediction, strategy); }
@Test public void testMacro() { System.out.println("Macro-Recall"); int[] truth = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
@Override public Column convert(BasicTypeDefine typeDefine) { PhysicalColumn.PhysicalColumnBuilder builder = PhysicalColumn.builder() .name(typeDefine.getName()) .sourceType(typeDefine.getColumnType()) .nullable(typeDefi...
@Test public void testConvertBinary() { BasicTypeDefine<Object> typeDefine = BasicTypeDefine.builder().name("test").columnType("blob").dataType("blob").build(); Column column = XuguTypeConverter.INSTANCE.convert(typeDefine); Assertions.assertEquals(typeDefine.getName(), colu...
@VisibleForTesting void dropPartitionsInternal(String catName, String dbName, String tblName, List<String> partNames, boolean allowSql, boolean allowJdo) throws MetaException, NoSuchObjectException { if (CollectionUtils.isEmpty(partNames)) { return; } new GetListHelper<Void>(catName, db...
@Test public void testDirectSQLDropPartitionsCleanup() throws Exception { createPartitionedTable(true, true); // Check, that every table in the expected state before the drop checkBackendTableSize("PARTITIONS", 3); checkBackendTableSize("PART_PRIVS", 3); checkBackendTableSize("PART_COL_PRIVS", 3...
public List<ChangeStreamRecord> toChangeStreamRecords( PartitionMetadata partition, ChangeStreamResultSet resultSet, ChangeStreamResultSetMetadata resultSetMetadata) { if (this.isPostgres()) { // In PostgresQL, change stream records are returned as JsonB. return Collections.singletonLi...
@Test public void testMappingStructRowToHeartbeatRecord() { final HeartbeatRecord heartbeatRecord = new HeartbeatRecord(Timestamp.ofTimeSecondsAndNanos(10L, 20), null); final Struct struct = recordsToStructWithStrings(heartbeatRecord); ChangeStreamResultSet resultSet = mock(ChangeStreamResultSet.c...
@Override public String getFieldDefinition( ValueMetaInterface v, String tk, String pk, boolean useAutoinc, boolean addFieldName, boolean addCr ) { String retval = ""; String fieldname = v.getName(); int length = v.getLength(); int precision = v.getPrecision(); ...
@Test public void testGetFieldDefinition() { assertEquals( "FOO DATETIME NULL", nativeMeta.getFieldDefinition( new ValueMetaTimestamp( "FOO" ), "", "", false, true, false ) ); assertEquals( "DATETIME NULL", nativeMeta.getFieldDefinition( new ValueMetaDate( "FOO" ), "", "", false, false, false ...
@Override public void handle(final RoutingContext routingContext) { // We must set it to allow chunked encoding if we're using http1.1 if (routingContext.request().version() == HttpVersion.HTTP_1_1) { routingContext.response().putHeader(TRANSFER_ENCODING, CHUNKED_ENCODING); } else if (routingContext...
@Test public void shouldSucceed_pushQuery() { // Given: when(publisher.isPullQuery()).thenReturn(false); final QueryStreamArgs req = new QueryStreamArgs("select * from foo emit changes;", Collections.emptyMap(), Collections.emptyMap(), Collections.emptyMap()); givenRequest(req); when(conne...
public static FactoryBuilder newFactoryBuilder() { return new FactoryBuilder(); }
@Test void injectKindFormats_cantBeSame() { assertThatThrownBy(() -> B3Propagation.newFactoryBuilder() .injectFormats(Span.Kind.CLIENT, Format.MULTI, Format.MULTI)) .isInstanceOf(IllegalArgumentException.class); }
public Set<LongPair> items() { Set<LongPair> items = new HashSet<>(this.size); forEach((item1, item2) -> items.add(new LongPair(item1, item2))); return items; }
@Test public void testItems() { GrowablePriorityLongPairQueue queue = new GrowablePriorityLongPairQueue(); int n = 100; int limit = 10; for (int i = 0; i < n; i++) { queue.add(i, i); } Set<LongPair> items = queue.items(); Set<LongPair> limitItems...
public static RestSettingBuilder get(final String id) { return get(eq(checkId(id))); }
@Test public void should_throw_exception_for_resource_name_with_space() { assertThrows(IllegalArgumentException.class, () -> server.resource("hello world", get().response("hello"))); }
@Override public void registerHints(@NonNull RuntimeHints hints, @Nullable ClassLoader classLoader) { var chatTypes = Set.of(AbstractMessage.class, AssistantMessage.class, ToolResponseMessage.class, Message.class, MessageType.class, UserMessage.class, SystemMessage.class, FunctionCallbackContext.class, Func...
@Test void core() { var runtimeHints = new RuntimeHints(); var springAiCore = new SpringAiCoreRuntimeHints(); springAiCore.registerHints(runtimeHints, null); assertThat(runtimeHints).matches(resource().forResource("embedding/embedding-model-dimensions.properties")); assertThat(runtimeHints).matches(reflecti...
public ValidationResult validateMessagesAndAssignOffsets(PrimitiveRef.LongRef offsetCounter, MetricsRecorder metricsRecorder, BufferSupplier bufferSupplier) { if (sourceCompressionType == Co...
@Test public void testRelativeOffsetAssignmentNonCompressedV1() { long now = System.currentTimeMillis(); MemoryRecords records = createRecords(RecordBatch.MAGIC_VALUE_V1, now, Compression.NONE); long offset = 1234567; checkOffsets(records, 0); MemoryRecords messageWithOffse...
public static List<Group> enumerateFrom(Group root) { List<Group> leaves = new ArrayList<>(); visitNode(root, leaves); return leaves; }
@Test void singleLeafIsEnumerated() throws Exception { Group g = new Group(0, "donkeykong", dummyDistribution()); Group child = new Group(1, "mario"); g.addSubGroup(child); List<Group> leaves = LeafGroups.enumerateFrom(g); assertThat(leaves.size(), is(1)); assertThat...
public static WebServiceClient getWebServiceClient() { return instance; }
@Test void testGetWebServiceClient() throws Exception { Configuration conf = new Configuration(); conf.set(YarnConfiguration.YARN_HTTP_POLICY_KEY, "HTTPS_ONLY"); WebServiceClient.initialize(conf); WebServiceClient client = WebServiceClient.getWebServiceClient(); assertNotNull(client.getSSLFactory(...
Future<Boolean> canRollController(int nodeId) { LOGGER.debugCr(reconciliation, "Determining whether controller pod {} can be rolled", nodeId); return describeMetadataQuorum().map(info -> { boolean canRoll = isQuorumHealthyWithoutNode(nodeId, info); if (!canRoll) { ...
@Test public void canRollActiveControllerOddSizedCluster(VertxTestContext context) { Map<Integer, OptionalLong> controllers = new HashMap<>(); controllers.put(1, OptionalLong.of(10000L)); controllers.put(2, OptionalLong.of(9500L)); controllers.put(3, OptionalLong.of(9700L)); ...
public SqlType getExpressionSqlType(final Expression expression) { return getExpressionSqlType(expression, Collections.emptyMap()); }
@Test public void shouldProcessTimeLiteral() { assertThat(expressionTypeManager.getExpressionSqlType(new TimeLiteral(new Time(1000))), is(SqlTypes.TIME)); }
@Override public void setParallelism(int parallelism) { checkParallelism(parallelism); Preconditions.checkArgument( parallelism <= maxParallelism, "Vertex's parallelism should be smaller than or equal to vertex's max parallelism."); Preconditions.checkState( ...
@Test void testSetParallelism() { DefaultVertexParallelismInfo info = new DefaultVertexParallelismInfo( ExecutionConfig.PARALLELISM_DEFAULT, 10, ALWAYS_VALID); // test set negative value assertThatThrownBy(() -> info.setParallelism(-1)) ...
@VisibleForTesting ImmutableList<EventWithContext> eventsFromAggregationResult(EventFactory eventFactory, AggregationEventProcessorParameters parameters, AggregationResult result) throws EventProcessorException { final ImmutableList.Builder<EventWithContext> eventsWithContext = ImmutableList.bui...
@Test public void testEventsFromAggregationResultWithEmptyResultAndNoConfiguredStreamsUsesAllStreamsAsSourceStreams() throws EventProcessorException { final DateTime now = DateTime.now(DateTimeZone.UTC); final AbsoluteRange timerange = AbsoluteRange.create(now.minusHours(1), now.minusHours(1).plusMi...
private static GuardedByExpression bind(JCTree.JCExpression exp, BinderContext context) { GuardedByExpression expr = BINDER.visit(exp, context); checkGuardedBy(expr != null, String.valueOf(exp)); checkGuardedBy(expr.kind() != Kind.TYPE_LITERAL, "Raw type literal: %s", exp); return expr; }
@Test public void explicitThisOuterClass() { assertThat( bind( "Inner", "this.lock", forSourceLines( "threadsafety/Test.java", "package threadsafety;", "class Outer {", " Ob...
public static CidrBlock fromString(String cidr) { String[] cidrParts = cidr.split("/"); if (cidrParts.length != 2) throw new IllegalArgumentException("Invalid CIDR block, expected format to be " + "'<ip address>/<prefix size>', but was '" + cidr + "'"); InetAddre...
@Test public void parse_from_string_test() { assertEquals(new CidrBlock(InetAddresses.forString("10.0.0.1"), 12), CidrBlock.fromString("10.0.0.1/12")); assertEquals(new CidrBlock(InetAddresses.forString("1234:5678::1"), 64), CidrBlock.fromString("1234:5678:0000::1/64")); }
public static Destination convertToJcsmpDestination(Solace.Destination destination) { if (destination.getType().equals(Solace.DestinationType.TOPIC)) { return topicFromName(checkNotNull(destination.getName())); } else if (destination.getType().equals(Solace.DestinationType.QUEUE)) { return queueFrom...
@Test public void testTopicEncoding() { MockSessionService mockClientService = new MockSessionService( index -> { List<BytesXMLMessage> messages = ImmutableList.of( SolaceDataUtils.getBytesXmlMessage("payload_test0", "450"), ...
@Override public boolean process(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { if (TokenReloadAction.tokenReloadEnabled()) { String pathInfo = request.getPathInfo(); if (pathInfo != null && pathInfo.eq...
@Test public void crumbExclusionChecksRequestPath() throws Exception { System.setProperty("casc.reload.token", "someSecretValue"); TokenReloadCrumbExclusion crumbExclusion = new TokenReloadCrumbExclusion(); assertFalse(crumbExclusion.process(new MockHttpServletRequest("/reload-configuratio...