focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override public long longValue() { return (long) value; }
@Override @Test void testLongValue() { new LongValueTester().runTests(); }
public void set(String name, String value) { List<String> values = headers.get(name); if (values == null) { values = new ArrayList<>(1); headers.put(name, values); } else { values.clear(); } values.add(value); }
@Test public void testSet() { HttpHeaders headers = new HttpHeaders(2); headers.set("Connection", "close"); headers.set("Connection", "Keep-Alive"); headers.set("Accept-Encoding", "gzip, deflate"); Assert.assertEquals("Keep-Alive", headers.get("Connection")); Assert....
public static boolean isFalse(Boolean b) { return b != null && !b; }
@Test public void testIsFalse() { Assert.assertTrue(CommonUtils.isFalse("false")); Assert.assertTrue(CommonUtils.isFalse("False")); Assert.assertFalse(CommonUtils.isFalse("null")); Assert.assertFalse(CommonUtils.isFalse("")); Assert.assertFalse(CommonUtils.isFalse("xxx")); ...
public static List<RlpType> asRlpValues( RawTransaction rawTransaction, Sign.SignatureData signatureData) { return rawTransaction.getTransaction().asRlpValues(signatureData); }
@Test public void testEtherTransactionAsRlpValues() { List<RlpType> rlpStrings = TransactionEncoder.asRlpValues( createEtherTransaction(), new Sign.SignatureData((byte) 0, new byte[32], new byte[32])); assertEquals(rlpStrings.size(), (9...
public static SerdeFeatures of(final SerdeFeature... features) { return new SerdeFeatures(ImmutableSet.copyOf(features)); }
@Test public void shouldReturnFeatureFromFindAnyOnAMatch() { assertThat(SerdeFeatures.of(WRAP_SINGLES) .findAny(WRAPPING_FEATURES), is(Optional.of(WRAP_SINGLES))); assertThat(SerdeFeatures.of(UNWRAP_SINGLES) .findAny(WRAPPING_FEATURES), is(Optional.of(UNWRAP_SINGLES))); }
@Nullable public Float getFloatValue(@FloatFormat final int formatType, @IntRange(from = 0) final int offset) { if ((offset + getTypeLen(formatType)) > size()) return null; switch (formatType) { case FORMAT_SFLOAT -> { if (mValue[offset + 1] == 0x07 && mValue[offset] == (byte) 0xFE) return F...
@Test public void setValue_SFLOAT_negativeInfinity() { final MutableData data = new MutableData(new byte[2]); data.setValue(Float.NEGATIVE_INFINITY, Data.FORMAT_SFLOAT, 0); final float value = data.getFloatValue(Data.FORMAT_SFLOAT, 0); assertEquals(Float.NEGATIVE_INFINITY, value, 0.00); }
public UiTopoLayout offsetX(double offsetX) { this.offsetX = offsetX; return this; }
@Test public void setXOff() { mkOtherLayout(); layout.offsetX(23.4); assertEquals("wrong x-offset", 23.4, layout.offsetX(), DELTA); }
public static Path getSegmentPath( String basePath, TieredStoragePartitionId partitionId, int subpartitionId, long segmentId) { String subpartitionPath = getSubpartitionPath(basePath, partitionId, subpartitionId); return new Path(subpartitionPath, SEGMENT_...
@Test void testGetSegmentPath() { TieredStoragePartitionId partitionId = TieredStorageIdMappingUtils.convertId(new ResultPartitionID()); int subpartitionId = 0; int segmentId = 1; String segmentPath = SegmentPartitionFile.getSegmentPath( ...
@Override public QueryHeader build(final QueryResultMetaData queryResultMetaData, final ShardingSphereDatabase database, final String columnName, final String columnLabel, final int columnIndex) throws SQLException { String schemaName = null == database ? "" : database.getName()...
@Test void assertBuildWithoutPrimaryKeyColumn() throws SQLException { QueryResultMetaData queryResultMetaData = createQueryResultMetaData(); assertFalse(new MySQLQueryHeaderBuilder().build(queryResultMetaData, createDatabase(), queryResultMetaData.getColumnName(2), queryResultMetaData.getColumnLabel...
public static void localRunnerNotification(JobConf conf, JobStatus status) { JobEndStatusInfo notification = createNotification(conf, status); if (notification != null) { do { try { int code = httpNotification(notification.getUri(), notification.getTimeout()); if ...
@Test public void testNotificationTimeout() throws InterruptedException { Configuration conf = new Configuration(); // Reduce the timeout to 1 second conf.setInt("mapreduce.job.end-notification.timeout", 1000); JobStatus jobStatus = createTestJobStatus( "job_20130313155005308_0001", JobStatus...
@Override public void process(Tuple input) { String key = filterMapper.getKeyFromTuple(input); boolean found; JedisCommandsContainer jedisCommand = null; try { jedisCommand = getInstance(); switch (dataType) { case STRING: ...
@Test void smokeTest_zrank_isMember() { // Define input key final String setKey = "ThisIsMySetKey"; final String inputKey = "ThisIsMyKey"; // Ensure key does exist in redis jedisHelper.zrank(setKey, 2, inputKey); // Create an input tuple final Map<String, Ob...
public static String inputStreamToString(InputStream inputStream, Charset charset) throws IOException { if (inputStream != null && inputStream.available() != -1) { ByteArrayOutputStream result = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int length; ...
@Test public void testInputStreamToString_withExpected() throws IOException { String expected = "test data"; InputStream anyInputStream = new ByteArrayInputStream(expected.getBytes(StandardCharsets.UTF_8)); String actual = StringUtils.inputStreamToString(anyInputStream, StandardCharsets.UTF_...
public static String getRecordReaderClassName(String fileFormatStr) { return DEFAULT_RECORD_READER_CLASS_MAP.get(fileFormatStr.toUpperCase()); }
@Test public void testGetRecordReaderClassName() { assertEquals(getRecordReaderClassName("avro"), DEFAULT_AVRO_RECORD_READER_CLASS); assertEquals(getRecordReaderClassName("gzipped_avro"), DEFAULT_AVRO_RECORD_READER_CLASS); assertEquals(getRecordReaderClassName("csv"), DEFAULT_CSV_RECORD_READER_CLASS); ...
@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 ValueMetaDate( "FOO" ), "", "", false, true, false ) ); assertEquals( "DATETIME NULL", nativeMeta.getFieldDefinition( new ValueMetaTimestamp( "FOO" ), "", "", false, false, false ...
@Override public void doFilter(HttpRequest request, HttpResponse response, FilterChain chain) throws IOException { try { userSession.checkIsSystemAdministrator(); } catch (ForbiddenException e) { AuthenticationError.handleError(request, response, "User needs to be logged in as system administrator...
@Test public void do_filter_as_not_admin() throws IOException { userSession.logIn(); HttpRequest servletRequest = mock(HttpRequest.class); HttpResponse servletResponse = mock(HttpResponse.class); FilterChain filterChain = mock(FilterChain.class); String callbackUrl = "http://localhost:9000/api/val...
@Override @CacheEvict(cacheNames = RedisKeyConstants.DEPT_CHILDREN_ID_LIST, allEntries = true) // allEntries 清空所有缓存,因为操作一个部门,涉及到多个缓存 public Long createDept(DeptSaveReqVO createReqVO) { if (createReqVO.getParentId() == null) { createReqVO.setParentId(DeptDO.PARENT_ID_ROOT); ...
@Test public void testCreateDept() { // 准备参数 DeptSaveReqVO reqVO = randomPojo(DeptSaveReqVO.class, o -> { o.setId(null); // 防止 id 被设置 o.setParentId(DeptDO.PARENT_ID_ROOT); o.setStatus(randomCommonStatus()); }); // 调用 Long deptId = deptServ...
@VisibleForTesting void checkNoPendingTasks(DbSession dbSession, EntityDto entityDto) { //This check likely can be removed when we remove the column 'private' from components table in SONAR-20126. checkState(countPendingTask(dbSession, entityDto.getKey()) == 0, "Component visibility can't be changed as long a...
@Test void checkNoPendingTasks_whenAnyOtherTaskInQueue_throws() { EntityDto entityDto = mockEntityDto(); when(dbClient.entityDao().selectByKey(dbSession, entityDto.getKey())).thenReturn(Optional.of(entityDto)); mockCeQueueDto("ANYTHING", entityDto.getUuid()); assertThatIllegalStateException() ...
private KsqlScalarFunction createFunction( final Class theClass, final UdfDescription udfDescriptionAnnotation, final Udf udfAnnotation, final Method method, final String path, final String sensorName, final Class<? extends Kudf> udfClass ) { // sanity check FunctionL...
@Test @SuppressWarnings("rawtypes") public void shouldInvokeUdafWhenMethodHasArgs() throws Exception { final UdafFactoryInvoker creator = createUdafLoader().createUdafFactoryInvoker( TestUdaf.class.getMethod( "createSumLengthString", String.class), FunctionName.of...
public void findIntersections(Rectangle query, Consumer<T> consumer) { IntArrayList todoNodes = new IntArrayList(levelOffsets.length * degree); IntArrayList todoLevels = new IntArrayList(levelOffsets.length * degree); int rootLevel = levelOffsets.length - 1; int rootIndex = levelOff...
@Test public void testSingletonFlatbushXY() { // Because mixing up x and y is easy to do... List<Rectangle> items = ImmutableList.of(new Rectangle(0, 10, 1, 11)); Flatbush<Rectangle> rtree = new Flatbush<>(items.toArray(new Rectangle[] {})); // hit assertEquals(findInter...
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 cannotRollActiveControllerWith1FollowerBehindEvenSizedCluster(VertxTestContext context) { Map<Integer, OptionalLong> controllers = new HashMap<>(); controllers.put(1, OptionalLong.of(10000L)); controllers.put(2, OptionalLong.of(7000L)); controllers.put(3, OptionalLo...
public static Document buildNamespaceAwareDocument(File xml) throws SAXException, ParserConfigurationException, IOException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); factory.setIgnoringElementContentWhitespace(true); ...
@Test public void testBuildNamespaceAwareDocument() throws Exception { assertNotNull(XmlHelper.buildNamespaceAwareDocument(ResourceUtils.getResourceAsFile("xmls/empty.xml"))); }
@Override public String requestMessageForCheckout(SCMPropertyConfiguration scmConfiguration, String destinationFolder, SCMRevision revision) { Map configuredValues = new LinkedHashMap(); configuredValues.put("scm-configuration", jsonResultMessageHandler.configurationToMap(scmConfiguration)); ...
@Test public void shouldBuildRequestBodyForCheckoutRequest() throws Exception { Date timestamp = new SimpleDateFormat(DATE_FORMAT).parse("2011-07-13T19:43:37.100Z"); Map data = new LinkedHashMap(); data.put("dataKeyOne", "data-value-one"); data.put("dataKeyTwo", "data-value-two"); ...
public static boolean isIpAddress(String ipAddress) { return isMatch(IP_REGEX, ipAddress); }
@Test public void testIp() { Assert.assertEquals(true, PatternKit.isIpAddress("192.168.1.1")); Assert.assertEquals(false, PatternKit.isIpAddress("256.255.255.0")); }
@SuppressFBWarnings("NP_NONNULL_PARAM_VIOLATION") // Not a bug synchronized CompletableFuture<Void> getFutureForSequenceNumber(final long seqNum) { if (seqNum <= lastCompletedSequenceNumber) { return CompletableFuture.completedFuture(null); } return sequenceNumberFutures.computeIfAbsent(seqNum, k ->...
@Test public void shouldReturnFutureForNewSequenceNumber() { // When: final CompletableFuture<Void> future = futureStore.getFutureForSequenceNumber(2); // Then: assertFutureIsNotCompleted(future); }
@Override public String getPipelineStatusMessage() { return String.format("Preparing to schedule (%s/%s)", 0, numberOfStages()); }
@Test public void shouldUnderstandPipelineStatusMessage() { StageInstanceModels stages = new StageInstanceModels(); stages.addFutureStage("unit1", false); stages.addFutureStage("unit2", false); PipelineInstanceModel pipeline = PipelineInstanceModel.createPreparingToSchedule("pipelin...
@Override public BasicTypeDefine reconvert(Column column) { BasicTypeDefine.BasicTypeDefineBuilder builder = BasicTypeDefine.builder() .name(column.getName()) .nullable(column.isNullable()) .comment(column.getComment()) ...
@Test public void testReconvertDecimal() { Column column = PhysicalColumn.builder().name("test").dataType(new DecimalType(0, 0)).build(); BasicTypeDefine typeDefine = OracleTypeConverter.INSTANCE.reconvert(column); Assertions.assertEquals(column.getName(), typeDefine.getName...
@Override public String getSignature(String baseString, String apiSecret, String tokenSecret) { try { final Signature signature = Signature.getInstance(RSA_SHA1); signature.initSign(privateKey); signature.update(baseString.getBytes(UTF8)); return Base64.encode...
@Test public void shouldReturnSignature() { final String apiSecret = "api secret"; final String tokenSecret = "token secret"; final String baseString = "base string"; final String signature = "LUNRzQAlpdNyM9mLXm96Va6g/qVNnEAb7p7K1KM0g8IopOFQJPoOO7cvppgt7w3QyhijWJnCmvqXaaIAGrqvd" ...
public long getTotalBatchMaxBytes() { if (this.produceAccumulator == null) { return 0; } return produceAccumulator.getTotalBatchMaxBytes(); }
@Test public void assertTotalBatchMaxBytes() throws NoSuchFieldException, IllegalAccessException { setProduceAccumulator(true); assertEquals(0L, producer.getTotalBatchMaxBytes()); }
@Override public GetContainerReportResponse getContainerReport( GetContainerReportRequest request) throws YarnException, IOException { ContainerId containerId = request.getContainerId(); try { GetContainerReportResponse response = GetContainerReportResponse.newInstance(history ...
@Test void testContainerReport() throws IOException, YarnException { ApplicationId appId = ApplicationId.newInstance(0, 1); ApplicationAttemptId appAttemptId = ApplicationAttemptId.newInstance(appId, 1); ContainerId containerId = ContainerId.newContainerId(appAttemptId, 1); GetContainerReportR...
public static <T> ThrowingConsumer<StreamRecord<T>, Exception> getRecordProcessor( Input<T> input) { boolean canOmitSetKeyContext; if (input instanceof AbstractStreamOperator) { canOmitSetKeyContext = canOmitSetKeyContext((AbstractStreamOperator<?>) input, 0); } else { ...
@Test void testOverrideSetKeyContextElementForOneInputStreamOperator() throws Exception { // test no override NoOverrideOneInputStreamOperator noOverride = new NoOverrideOneInputStreamOperator(); RecordProcessorUtils.getRecordProcessor(noOverride).accept(new StreamRecord<>("test")); ...
public FEELFnResult<Boolean> invoke(@ParameterName("range1") Range range1, @ParameterName("range2") Range range2) { if (range1 == null) { return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "range1", "cannot be null")); } if (range2 == null) { return FE...
@Test void invokeParamIsNull() { FunctionTestUtil.assertResultError(overlapsFunction.invoke(null, new RangeImpl()), InvalidParametersEvent.class); FunctionTestUtil.assertResultError(overlapsFunction.invoke(new RangeImpl(), null), InvalidParametersEvent.class); }
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 testInvalidNumberOfWorkerHarnessThreads() throws IOException { DataflowPipelineOptions options = buildPipelineOptions(); options.as(DataflowPipelineDebugOptions.class).setNumberOfWorkerHarnessThreads(-1); thrown.expect(IllegalArgumentException.class); thrown.expectMessage("Number of...
IdBatchAndWaitTime newIdBaseLocal(int batchSize) { return newIdBaseLocal(Clock.currentTimeMillis(), getNodeId(), batchSize); }
@Test public void test_idsOrdered() { long lastId = -1; for (long now = DEFAULT_EPOCH_START; now < DEFAULT_EPOCH_START + (1L << DEFAULT_BITS_TIMESTAMP); now += 365L * 24L * 60L * 60L * 1000L) { long base = gen.newIdBaseLocal(now, 1234, 1).idBatch.base(); ...
public SqlType getExpressionSqlType(final Expression expression) { return getExpressionSqlType(expression, Collections.emptyMap()); }
@Test public void shouldHandleNestedLambdas() { // Given: givenUdfWithNameAndReturnType("TRANSFORM", SqlTypes.INTEGER); when(function.parameters()).thenReturn( ImmutableList.of( ArrayType.of(LongType.INSTANCE), IntegerType.INSTANCE, LambdaType.of( ...
public static <T> T getBean(Class<T> interfaceClass, Class typeClass) { Object object = serviceMap.get(interfaceClass.getName() + "<" + typeClass.getName() + ">"); if(object == null) return null; if(object instanceof Object[]) { return (T)Array.get(object, 0); } else { ...
@Test public void testSingleFromArray() { // get the first object from an array of impelementation in service.yml E e = SingletonServiceFactory.getBean(E.class); Assert.assertEquals("e1", e.e()); }
@Override @SuppressWarnings("deprecation") public HttpClientOperations addHandler(ChannelHandler handler) { super.addHandler(handler); return this; }
@Test void addNamedEncoderReplaysLastHttp() { ByteBuf buf = Unpooled.copiedBuffer("{\"foo\":1}", CharsetUtil.UTF_8); EmbeddedChannel channel = new EmbeddedChannel(); new HttpClientOperations(() -> channel, ConnectionObserver.emptyListener(), ClientCookieEncoder.STRICT, ClientCookieDecoder.STRICT, ReactorNett...
void pruneMissingPeers() { prunePeersTimer.record(() -> { final Set<String> peerIds = presenceCluster.withCluster( connection -> connection.sync().smembers(MANAGER_SET_KEY)); peerIds.remove(managerId); for (final String peerId : peerIds) { final boolean peerMissing = presenceClu...
@Test void testPruneMissingPeers() { final String presentPeerId = UUID.randomUUID().toString(); final String missingPeerId = UUID.randomUUID().toString(); REDIS_CLUSTER_EXTENSION.getRedisCluster().useCluster(connection -> { connection.sync().sadd(ClientPresenceManager.MANAGER_SET_KEY, presentPeerId...
public static int AUG_CCITT(@NonNull final byte[] data, final int offset, final int length) { return CRC(0x1021, 0x1D0F, data, offset, length, false, false, 0x0000); }
@Test public void AUG_CCITT_empty() { final byte[] data = new byte[0]; assertEquals(0x1D0F, CRC16.AUG_CCITT(data, 0, 0)); }
@Override public void validate(final Analysis analysis) { failPersistentQueryOnWindowedTable(analysis); QueryValidatorUtil.validateNoUserColumnsWithSameNameAsPseudoColumns(analysis); }
@Test public void shouldNotThrowOnPersistentPushQueryOnWindowedStream() { // Given: givenPersistentQuery(); givenSourceStream(); givenWindowedSource(); // When/Then: validator.validate(analysis); }
public static ExistsSubqueryExpression bind(final ExistsSubqueryExpression segment, final SQLStatementBinderContext binderContext, final Map<String, TableSegmentBinderContext> tableBinderContexts) { SubquerySegment boundSubquery = SubquerySegmentBinder.bind(segmen...
@Test void assertBindExistsSubqueryExpression() { MySQLSelectStatement selectStatement = new MySQLSelectStatement(); selectStatement.setProjections(new ProjectionsSegment(0, 0)); ExistsSubqueryExpression existsSubqueryExpression = new ExistsSubqueryExpression(0, 0, new SubquerySegment(0, 0, ...
@Override public DataSerializableFactory createFactory() { return typeId -> switch (typeId) { case MAP_REPLICATION_UPDATE -> new WanMapAddOrUpdateEvent(); case MAP_REPLICATION_REMOVE -> new WanMapRemoveEvent(); case WAN_MAP_ENTRY_VIEW -> new WanMapEntryView<>(); ...
@Test(expected = IllegalArgumentException.class) public void testInvalidType() { WanDataSerializerHook hook = new WanDataSerializerHook(); hook.createFactory().create(999); }
public static List<Import> getImportList(final List<String> importCells) { final List<Import> importList = new ArrayList<>(); if ( importCells == null ) { return importList; } for( String importCell: importCells ){ final StringTokenizer tokens = new StringTokeniz...
@Test public void getImportList_maniValues() { List<Import> list = getImportList(List.of("", "com.something.Yeah, com.something.No,com.something.yeah.*")); assertThat(list).hasSize(3).extracting(x -> x.getClassName()).containsExactly("com.something.Yeah", "com.something.No", "com.something....
public AdditionalServletWithClassLoader load( AdditionalServletMetadata metadata, String narExtractionDirectory) throws IOException { final File narFile = metadata.getArchivePath().toAbsolutePath().toFile(); NarClassLoader ncl = NarClassLoaderBuilder.builder() .narFile(narFi...
@Test public void testLoadEventListener() throws Exception { AdditionalServletDefinition def = new AdditionalServletDefinition(); def.setAdditionalServletClass(MockAdditionalServlet.class.getName()); def.setDescription("test-proxy-listener"); String archivePath = "/path/to/proxy/lis...
@Override public byte[] fromConnectHeader(String topic, String headerKey, Schema schema, Object value) { return fromConnectData(topic, schema, value); }
@Test public void testNullHeaderValueToBytes() { assertNull(converter.fromConnectHeader(TOPIC, "hdr", Schema.OPTIONAL_STRING_SCHEMA, null)); }
@Override protected void doStart() throws Exception { super.doStart(); LOG.debug("Creating connection to Azure ServiceBus"); client = getEndpoint().getServiceBusClientFactory().createServiceBusProcessorClient(getConfiguration(), this::processMessage, this::processError); ...
@Test void consumerPropagatesApplicationPropertiesToMessageHeaders() throws Exception { try (ServiceBusConsumer consumer = new ServiceBusConsumer(endpoint, processor)) { consumer.doStart(); verify(client).start(); verify(clientFactory).createServiceBusProcessorClient(any(...
@Override public void prepareContainer(ContainerRuntimeContext ctx) throws ContainerExecutionException { @SuppressWarnings("unchecked") List<String> localDirs = ctx.getExecutionAttribute(CONTAINER_LOCAL_DIRS); @SuppressWarnings("unchecked") Map<org.apache.hadoop.fs.Path, List<String>> r...
@Test public void testDeniedWhitelistGroup() throws ContainerExecutionException { String[] inputCommand = { "$JAVA_HOME/bin/java jar MyJob.jar" }; List<String> commands = Arrays.asList(inputCommand); conf.set(YarnConfiguration.YARN_CONTAINER_SANDBOX_WHITELIST_GROUP, WHITELIST_GROUP);...
@VisibleForTesting static Map<Severity, List<String>> checkNoticeFile( Map<String, Set<Dependency>> modulesWithShadedDependencies, String moduleName, @Nullable NoticeContents noticeContents) { final Map<Severity, List<String>> problemsBySeverity = new HashMap<>(); ...
@Test void testCheckNoticeFileRejectsEmptyFile() { assertThat(NoticeFileChecker.checkNoticeFile(Collections.emptyMap(), "test", null)) .containsOnlyKeys(NoticeFileChecker.Severity.CRITICAL); }
@Override @Nullable public V put(@Nullable K key, @Nullable V value) { return put(key, value, true); }
@Test void shouldGetValues() { this.map.put(123, "123"); this.map.put(456, null); this.map.put(null, "789"); List<String> actual = new ArrayList<>(this.map.values()); List<String> expected = new ArrayList<>(); expected.add("123"); expected.add(null); expected.add("789"); actual.sor...
@Override public Map<Errors, Integer> errorCounts() { HashMap<Errors, Integer> counts = new HashMap<>(); updateErrorCounts(counts, Errors.forCode(data.errorCode())); return counts; }
@Test public void testErrorCountsReturnsOneError() { GetTelemetrySubscriptionsResponseData data = new GetTelemetrySubscriptionsResponseData() .setErrorCode(Errors.CLUSTER_AUTHORIZATION_FAILED.code()); data.setErrorCode(Errors.INVALID_CONFIG.code()); GetTelemetrySubscriptions...
public static List<Date> matchedDates(String patternStr, Date start, int count, boolean isMatchSecond) { return matchedDates(patternStr, start, DateUtil.endOfYear(start), count, isMatchSecond); }
@Test public void matchedDatesTest3() { //测试最后一天 List<Date> matchedDates = CronPatternUtil.matchedDates("0 0 */1 L * *", DateUtil.parse("2018-10-30 23:33:22"), 5, true); assertEquals(5, matchedDates.size()); assertEquals("2018-10-31 00:00:00", matchedDates.get(0).toString()); assertEquals("2018-10-31 01:00:0...
public static void updateKeyForBlobStore(Map<String, Object> conf, BlobStore blobStore, CuratorFramework zkClient, String key, NimbusInfo nimbusDetails) { try { // Most of clojure tests currently try to access the blobs using getBlob. Since, updateKeyForB...
@Test public void testUpdateKeyForBlobStore_nodeWithNullChildren() { zkClientBuilder.withExists(BLOBSTORE_KEY, true); zkClientBuilder.withGetChildren(BLOBSTORE_KEY, (List<String>) null); BlobStoreUtils.updateKeyForBlobStore(conf, blobStore, zkClientBuilder.build(), KEY, nimbusDetails); ...
public static DeleteAclsRequest parse(ByteBuffer buffer, short version) { return new DeleteAclsRequest(new DeleteAclsRequestData(new ByteBufferAccessor(buffer), version), version); }
@Test public void shouldRoundTripV1() { final DeleteAclsRequest original = new DeleteAclsRequest.Builder( requestData(LITERAL_FILTER, PREFIXED_FILTER, ANY_FILTER) ).build(V1); final ByteBuffer buffer = original.serialize(); final DeleteAclsRequest result = DeleteAcls...
@Override public String convert(final BroadcastRuleConfiguration ruleConfig) { if (ruleConfig.getTables().isEmpty()) { return ""; } return String.format(CREATE_BROADCAST_TABLE_RULE, Joiner.on(",").join(ruleConfig.getTables())); }
@Test void assertConvert() { BroadcastRuleConfiguration ruleConfig = mock(BroadcastRuleConfiguration.class); when(ruleConfig.getTables()).thenReturn(Arrays.asList("t_province", "t_city")); String actual = new BroadcastRuleConfigurationToDistSQLConverter().convert(ruleConfig); assertT...
@Override protected void handleEndTxnOnPartition(CommandEndTxnOnPartition command) { checkArgument(state == State.Connected); final long requestId = command.getRequestId(); final String topic = command.getTopic(); final int txnAction = command.getTxnAction().getValue(); final...
@Test(expectedExceptions = IllegalArgumentException.class) public void shouldFailHandleEndTxnOnPartition() throws Exception { ServerCnx serverCnx = mock(ServerCnx.class, CALLS_REAL_METHODS); Field stateUpdater = ServerCnx.class.getDeclaredField("state"); stateUpdater.setAccessible(true); ...
protected Query<E> namedTypedQuery(String queryName) throws HibernateException { return currentSession().createNamedQuery(queryName, getEntityClass()); }
@Test void getsNamedTypedQueries() throws Exception { assertThat(dao.namedTypedQuery("query-name")) .isEqualTo(query); verify(session).createNamedQuery("query-name", String.class); }
@Override public void publish(ScannerReportWriter writer) { for (final DefaultInputFile inputFile : componentCache.allChangedFilesToPublish()) { File iofile = writer.getSourceFile(inputFile.scannerId()); try (OutputStream output = new BufferedOutputStream(new FileOutputStream(iofile)); InputS...
@Test public void cleanLineEnds() throws Exception { FileUtils.write(sourceFile, "\n2\r\n3\n4\r5", StandardCharsets.ISO_8859_1); publisher.publish(writer); File out = writer.getSourceFile(inputFile.scannerId()); assertThat(FileUtils.readFileToString(out, StandardCharsets.UTF_8)).isEqualTo("\n2\n3\n4...
@ConstantFunction(name = "bitand", argTypes = {TINYINT, TINYINT}, returnType = TINYINT) public static ConstantOperator bitandTinyInt(ConstantOperator first, ConstantOperator second) { return ConstantOperator.createTinyInt((byte) (first.getTinyInt() & second.getTinyInt())); }
@Test public void bitandTinyInt() { assertEquals(10, ScalarOperatorFunctions.bitandTinyInt(O_TI_10, O_TI_10).getTinyInt()); }
@Override public Optional<BufferOrEvent> getNext() throws IOException, InterruptedException { return getNextBufferOrEvent(true); }
@Test void testAvailability() throws IOException, InterruptedException { final SingleInputGate inputGate1 = createInputGate(1); TestInputChannel inputChannel1 = new TestInputChannel(inputGate1, 0, false, true); inputGate1.setInputChannels(inputChannel1); final SingleInputGate inputG...
@Override public PulsarClient build() throws PulsarClientException { checkArgument(StringUtils.isNotBlank(conf.getServiceUrl()) || conf.getServiceUrlProvider() != null, "service URL or service URL provider needs to be specified on the ClientBuilder object."); checkArgument(StringUtil...
@Test(expectedExceptions = IllegalArgumentException.class) public void testClientBuilderWithServiceUrlAndServiceUrlProviderNotSet() throws PulsarClientException { PulsarClient.builder().build(); }
@Override public List<byte[]> mGet(byte[]... keys) { if (isQueueing() || isPipelined()) { for (byte[] key : keys) { read(key, ByteArrayCodec.INSTANCE, RedisCommands.GET, key); } return null; } CommandBatchService es = new CommandBatchServi...
@Test public void testMGet() { Map<byte[], byte[]> map = new HashMap<>(); for (int i = 0; i < 10; i++) { map.put(("test" + i).getBytes(), ("test" + i*100).getBytes()); } connection.mSet(map); List<byte[]> r = connection.mGet(map.keySet().toArray(new byte[0][])); ...
@Override public TableEntryByTypeTransformer tableEntryByTypeTransformer() { return transformer; }
@Test void transforms_empties_with_correct_method() throws Throwable { Map<String, String> fromValue = singletonMap("key", "[empty]"); Method method = JavaDefaultDataTableEntryTransformerDefinitionTest.class.getMethod("correct_method", Map.class, Type.class); JavaDefaultDataTable...
@Override public List<Instance> selectInstances(String serviceName, boolean healthy) throws NacosException { return selectInstances(serviceName, new ArrayList<>(), healthy); }
@Test void testSelectInstances8() throws NacosException { //given String serviceName = "service1"; String groupName = "group1"; List<String> clusterList = Arrays.asList("cluster1", "cluster2"); //when client.selectInstances(serviceName, groupName, clusterList, true, f...
@Override public synchronized String getUri() { return String.format( "jdbc:%s://%s:%d%s%s", getJDBCPrefix(), this.getHost(), this.getPort(getJDBCPort()), initialized ? ";DatabaseName=" + databaseName : "", ";encrypt=true;trustServerCertificate=true;"); }
@Test public void testGetUriShouldReturnCorrectValue() { when(container.getHost()).thenReturn(HOST); when(container.getMappedPort( MSSQLResourceManager.DefaultMSSQLServerContainer.MS_SQL_SERVER_PORT)) .thenReturn(MAPPED_PORT); assertThat(testManager.getUri()) .matches( ...
public void setOuterJoinType(OuterJoinType outerJoinType) { this.outerJoinType = outerJoinType; }
@Test void testFullOuterJoinBuildingCorrectCrossProducts() throws Exception { final List<String> leftInput = Arrays.asList("foo", "foo", "foo", "bar", "bar", "foobar", "foobar"); final List<String> rightInput = Arrays.asList("foo", "foo", "bar", "bar", "bar", "barfoo"...
public void poll(RequestFuture<?> future) { while (!future.isDone()) poll(time.timer(Long.MAX_VALUE), future); }
@Test public void blockWhenPollConditionNotSatisfied() { long timeout = 4000L; NetworkClient mockNetworkClient = mock(NetworkClient.class); ConsumerNetworkClient consumerClient = new ConsumerNetworkClient(new LogContext(), mockNetworkClient, metadata, time, 100, 1000, Intege...
public static List<Event> computeEventDiff(final Params params) { final List<Event> events = new ArrayList<>(); emitPerNodeDiffEvents(createBaselineParams(params), events); emitWholeClusterDiffEvent(createBaselineParams(params), events); emitDerivedBucketSpaceStatesDiffEvents(params, ev...
@Test void derived_bucket_space_state_events_are_not_emitted_if_similar_to_baseline() { EventFixture f = EventFixture.createForNodes(3) .clusterStateBefore("distributor:3 storage:3") .derivedClusterStateBefore("default", "distributor:3 storage:3") .derivedClus...
@Override protected void doStart() throws Exception { super.doStart(); LOG.debug("Creating connection to Azure ServiceBus"); client = getEndpoint().getServiceBusClientFactory().createServiceBusProcessorClient(getConfiguration(), this::processMessage, this::processError); ...
@Test void synchronizationDoesNotDeadLetterMessageWhenReceiveModeIsReceiveAndDelete() throws Exception { try (ServiceBusConsumer consumer = new ServiceBusConsumer(endpoint, processor)) { when(configuration.getServiceBusReceiveMode()).thenReturn(ServiceBusReceiveMode.RECEIVE_AND_DELETE); ...
@Override public Photo get(Long key) { return _db.getData().get(key); }
@Test public void testResourceGet() { // because the test function will take arbitrary order // always create a photo and operate on that photo for a test function final Long id = createPhoto(); // validate all data are correct final Photo p = _res.get(id); Assert.assertNotNull(p); Asse...
public void onFragment(final DirectBuffer buffer, final int offset, final int length, final Header header) { final byte flags = header.flags(); if ((flags & UNFRAGMENTED) == UNFRAGMENTED) { delegate.onFragment(buffer, offset, length, header); } else { ...
@Test void shouldDoNotingIfMidArrivesWithoutBegin() { when(header.flags()) .thenReturn((byte)0) .thenReturn(FrameDescriptor.END_FRAG_FLAG); final UnsafeBuffer srcBuffer = new UnsafeBuffer(new byte[1024]); final int offset = 0; final int length = srcBuffer...
public static PageNumber page(int i) { return new PageNumber(i); }
@Test public void shouldUnderstandPageNumberAndLabel() { assertThat(Pagination.PageNumber.DOTS.getLabel(), is("...")); assertThat(Pagination.PageNumber.DOTS.getNumber(), is(-1)); assertThat(Pagination.page(5).getLabel(), is("5")); assertThat(Pagination.page(5).getNumber(), is(5)); ...
@Override public NSImage folderIcon(final Integer size) { NSImage folder = this.iconNamed("NSFolder", size); if(null == folder) { return this.iconNamed("NSFolder", size); } return folder; }
@Test public void testFolderIconAllSizes() { final NSImage icon = new NSImageIconCache().folderIcon(null); assertNotNull(icon); assertTrue(icon.isValid()); assertFalse(icon.isTemplate()); assertTrue(icon.representations().count().intValue() >= 1); }
@Override public ApiResult<TopicPartition, DeletedRecords> handleResponse( Node broker, Set<TopicPartition> keys, AbstractResponse abstractResponse ) { DeleteRecordsResponse response = (DeleteRecordsResponse) abstractResponse; Map<TopicPartition, DeletedRecords> completed...
@Test public void testHandlePartitionErrorResponse() { TopicPartition errorPartition = t0p0; Errors error = Errors.TOPIC_AUTHORIZATION_FAILED; Map<TopicPartition, Short> errorsByPartition = new HashMap<>(); errorsByPartition.put(errorPartition, error.code()); AdminApiHandler...
@SuppressWarnings("MethodMayBeStatic") // Non-static to support DI. public long parse(final String text) { final String date; final String time; final String timezone; if (text.contains("T")) { date = text.substring(0, text.indexOf('T')); final String withTimezone = text.substring(text.i...
@Test public void shouldParseDateWithHourMinuteSecond() { // When: assertThat(parser.parse("2020-12-02T13:59:58"), is(fullParse("2020-12-02T13:59:58.000+0000"))); assertThat(parser.parse("2020-12-02T13:59:58Z"), is(fullParse("2020-12-02T13:59:58.000+0000"))); }
@Override public Column convert(BasicTypeDefine typeDefine) { PhysicalColumn.PhysicalColumnBuilder builder = PhysicalColumn.builder() .name(typeDefine.getName()) .sourceType(typeDefine.getColumnType()) .nullable(typeDefi...
@Test public void testConvertChar() { BasicTypeDefine<Object> typeDefine = BasicTypeDefine.builder() .name("test") .columnType("CHARACTER") .dataType("CHARACTER") .length(1L) ...
public IssueQuery create(SearchRequest request) { try (DbSession dbSession = dbClient.openSession(false)) { final ZoneId timeZone = parseTimeZone(request.getTimeZone()).orElse(clock.getZone()); Collection<RuleDto> ruleDtos = ruleKeysToRuleId(dbSession, request.getRules()); Collection<String> rule...
@Test public void return_empty_results_if_not_allowed_to_search_for_subview() { ComponentDto view = db.components().insertPrivatePortfolio(); ComponentDto subView = db.components().insertComponent(newSubPortfolio(view)); SearchRequest request = new SearchRequest() .setComponentUuids(singletonList(su...
public String getName() { return name; }
@Test public void testGetName() { // Test the getName method assertEquals("EventName", event.getName()); }
@Override void execute() { String[] loc = getCl().getUpddateLocationParams(); Path newPath = new Path(loc[0]); Path oldPath = new Path(loc[1]); URI oldURI = oldPath.toUri(); URI newURI = newPath.toUri(); /* * validate input - Both new and old URI should contain valid host names and val...
@Test public void testNoScheme() throws Exception { exception.expect(IllegalStateException.class); exception.expectMessage("HiveMetaTool:A valid scheme is required in both old-loc and new-loc"); MetaToolTaskUpdateLocation t = new MetaToolTaskUpdateLocation(); t.setCommandLine(new HiveMetaToolCommandL...
protected String getHttpURL(Exchange exchange, Endpoint endpoint) { Object url = exchange.getIn().getHeader(Exchange.HTTP_URL); if (url instanceof String) { return (String) url; } else { Object uri = exchange.getIn().getHeader(Exchange.HTTP_URI); if (uri insta...
@Test public void testGetHttpURLFromEndpointUriWithAdditionalScheme() { Endpoint endpoint = Mockito.mock(Endpoint.class); Exchange exchange = Mockito.mock(Exchange.class); Message message = Mockito.mock(Message.class); Mockito.when(endpoint.getEndpointUri()).thenReturn("netty-http:"...
public SearchSourceBuilder create(SearchesConfig config) { return create(SearchCommand.from(config)); }
@Test void searchIncludesProperSourceFields() { final SearchSourceBuilder search = this.searchRequestFactory.create(ChunkCommand.builder() .indices(Collections.singleton("graylog_0")) .range(RANGE) .fields(List.of("foo", "bar")) .build()); ...
public void unset(PropertyKey key) { Preconditions.checkNotNull(key, "key"); mProperties.remove(key); }
@Test public void unset() { assertFalse(mConfiguration.isSet(PropertyKey.SECURITY_LOGIN_USERNAME)); mConfiguration.set(PropertyKey.SECURITY_LOGIN_USERNAME, "test"); assertTrue(mConfiguration.isSet(PropertyKey.SECURITY_LOGIN_USERNAME)); mConfiguration.unset(PropertyKey.SECURITY_LOGIN_USERNAME); ass...
public static HttpRequest newJDiscRequest(CurrentContainer container, HttpServletRequest servletRequest) { try { var jettyRequest = (Request) servletRequest; var jdiscHttpReq = HttpRequest.newServerRequest( container, getUri(servletRequest), ...
@Test final void illegal_host_throws_requestexception1() { try { HttpRequestFactory.newJDiscRequest( new MockContainer(), createMockRequest("http", "?", "/foo", "")); fail("Above statement should throw"); } catch (RequestException e) { ...
@SuppressWarnings("unchecked") static Object extractFromRecordValue(Object recordValue, String fieldName) { List<String> fields = Splitter.on('.').splitToList(fieldName); if (recordValue instanceof Struct) { return valueFromStruct((Struct) recordValue, fields); } else if (recordValue instanceof Map)...
@Test public void testExtractFromRecordValueMapNested() { Map<String, Object> id = ImmutableMap.of("key", 123L); Map<String, Object> data = ImmutableMap.of("id", id); Map<String, Object> val = ImmutableMap.of("data", data); Object result = RecordUtils.extractFromRecordValue(val, "data.id.key"); a...
@Override public Object deserialize(Asn1ObjectInputStream in, Class<? extends Object> type, Asn1ObjectMapper mapper) { final Asn1Entity entity = type.getAnnotation(Asn1Entity.class); final Object instance = ObjectUtils.newInstance(type); final Map<Strin...
@Test public void shouldDeserializeWithOptional() { assertEquals(new Set(1, 2, 3, 4), deserialize( new SetOfIdentifiedConverter(), Set.class, new byte[] { 0x30, 6, 0x06, 1, 44, 0x02, 1, 4, 0x30, 6, 0x06, 1, 83, 0x02, 1, 3, 0x30,9, 0x06, 1, 84, 0x02, 1, 1, 0x02, 1,...
public Optional<Table> getTable(TableName tableName) { return Optional.ofNullable(getTable(tableName.getCatalog(), tableName.getDb(), tableName.getTbl())); }
@Test public void testGetMetadataTable() throws Exception { new MockUp<IcebergHiveCatalog>() { @Mock boolean tableExists(String dbName, String tableName) { return true; } }; String createIcebergCatalogStmt = "create external catalog iceber...
public static void toLowerCase(StringValue string) { final char[] chars = string.getCharArray(); final int len = string.length(); for (int i = 0; i < len; i++) { chars[i] = Character.toLowerCase(chars[i]); } }
@Test void testToLowerCaseConverting() { StringValue testString = new StringValue("TEST"); StringValueUtils.toLowerCase(testString); assertThat((Object) testString).isEqualTo(new StringValue("test")); }
public String decode(byte[] val) { return codecs[0].decode(val, 0, val.length); }
@Test public void testDecodeKoreanLongText() { assertEquals(KOREAN_LONG_TEXT, ksx1001().decode(KOREAN_LONG_TEXT_NO_EXPLICIT_ESCSEQ_BYTES)); }
public static long heapMemoryFree() { return Math.subtractExact(heapMemoryMax(), heapMemoryUsed()); }
@Test public void heapMemoryFree() { long memoryUsed = MemoryUtil.heapMemoryFree(); Assert.assertNotEquals(0, memoryUsed); }
@Override public void pluginLoaded(GoPluginDescriptor pluginDescriptor) { if (notificationExtension.canHandlePlugin(pluginDescriptor.id())) { try { notificationPluginRegistry.registerPlugin(pluginDescriptor.id()); List<String> notificationsInterestedIn = notificat...
@Test public void shouldNotRegisterPluginInterestsOnPluginLoadIfPluginIfPluginIsNotOfNotificationType() { NotificationPluginRegistrar notificationPluginRegistrar = new NotificationPluginRegistrar(pluginManager, notificationExtension, notificationPluginRegistry); notificationPluginRegistrar.pluginLo...
public Optional<Measure> toMeasure(@Nullable MeasureDto measureDto, Metric metric) { requireNonNull(metric); if (measureDto == null) { return Optional.empty(); } Double value = measureDto.getValue(); String data = measureDto.getData(); switch (metric.getType().getValueType()) { case ...
@Test public void toMeasure_returns_no_value_if_dto_has_no_value_for_Boolean_metric() { Optional<Measure> measure = underTest.toMeasure(EMPTY_MEASURE_DTO, SOME_BOOLEAN_METRIC); assertThat(measure).isPresent(); assertThat(measure.get().getValueType()).isEqualTo(Measure.ValueType.NO_VALUE); }
public Response listLogFiles(String user, Integer port, String topologyId, String callback, String origin) throws IOException { List<Path> fileResults = null; if (topologyId == null) { if (port == null) { fileResults = workerLogs.getAllLogsForRootDir(); } else { ...
@Test public void testListLogFiles() throws IOException { String rootPath = Files.createTempDirectory("workers-artifacts").toFile().getCanonicalPath(); File file1 = new File(String.join(File.separator, rootPath, "topoA", "1111"), "worker.log"); File file2 = new File(String.join(File.separato...
@WorkerThread @Override public Unit call() throws IOException, StreamNotFoundException, ShellNotRunningException, IllegalArgumentException { OutputStream outputStream; File destFile = null; switch (fileAbstraction.scheme) { case CONTENT: Objects.require...
@Test @Config(shadows = {ShellNotRunningRootUtils.class}) public void testWriteFileRootShellNotRunning() throws IOException, StreamNotFoundException, ShellNotRunningException { File file = new File(Environment.getExternalStorageDirectory(), "test.txt"); Uri uri = Uri.fromFile(file); File cacheFile...
public List<R> scanForResourcesPath(Path resourcePath) { requireNonNull(resourcePath, "resourcePath must not be null"); List<R> resources = new ArrayList<>(); pathScanner.findResourcesForPath( resourcePath, canLoad, processResource(DEFAULT_PACKAGE_NAME, NULL_F...
@Test @DisabledOnOs(value = OS.WINDOWS, disabledReason = "Only works if repository is explicitly cloned activated symlinks and " + "developer mode in windows is activated") void scanForResourcesPathSymlink() { File file = new File("src/test/resource-symlink/test/resource....
@Override public void onSuccess(T result) { markTimings(); _callback.onSuccess(result); }
@Test(dataProvider = "timingImportanceThreshold") public void testBuilder(TimingImportance timingImportanceThreshold) { final RequestContext requestContext = new RequestContext(); if (timingImportanceThreshold != null) { requestContext.putLocalAttr(TimingContextUtil.TIMING_IMPORTANCE_THRESHOLD_KEY...
@Override public UserIdentity login(String username, Object credentials, ServletRequest request) { if (!(credentials instanceof SignedJWT)) { return null; } if (!(request instanceof HttpServletRequest)) { return null; } SignedJWT jwtToken = (SignedJWT) credentials; JWTClaimsSet cl...
@Test public void testFailSignatureValidation() throws Exception { UserStore testUserStore = new UserStore(); testUserStore.addUser(TEST_USER, SecurityUtils.NO_CREDENTIAL, new String[] {"USER"}); TokenGenerator.TokenAndKeys tokenAndKeys = TokenGenerator.generateToken(TEST_USER); // This will be signed...
@PublicAPI(usage = ACCESS) public static PackageMatcher of(String packageIdentifier) { return new PackageMatcher(packageIdentifier); }
@Test public void should_reject_more_than_two_dots_in_a_row() { assertThatThrownBy(() -> PackageMatcher.of("some...pkg")) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Package Identifier may not contain more than two '.' in a row"); }
@Override public boolean evaluate(Map<String, Object> values) { Boolean toReturn = null; for (KiePMMLPredicate kiePMMLPredicate : kiePMMLPredicates) { Boolean evaluation = kiePMMLPredicate.evaluate(values); switch (booleanOperator) { case OR: ...
@Test void evaluateCompoundPredicateOr() { ARRAY_TYPE arrayType = ARRAY_TYPE.STRING; List<Object> stringValues = getObjects(arrayType, 4); KiePMMLSimpleSetPredicate kiePMMLSimpleSetPredicateString = getKiePMMLSimpleSetPredicate(SIMPLE_SET_PREDICATE_STRING_NAME, ...
public static String removeModifierSuffix(String fullName) { int indexOfFirstOpeningToken = fullName.indexOf(MODIFIER_OPENING_TOKEN); if (indexOfFirstOpeningToken == -1) { return fullName; } int indexOfSecondOpeningToken = fullName.lastIndexOf(MODIFIER_OPENING_TOKEN); ...
@Test public void removeModifierSuffix_whenSuffixIsPresent_thenReturnStringWithoutSuffix() { String attributeWithModifier = "foo[*]"; String result = SuffixModifierUtils.removeModifierSuffix(attributeWithModifier); assertEquals("foo", result); }
public ActionPermissionResolver getActionPermissionResolver() { return actionPermissionResolver; }
@Test public void testDefaults() { ActionPermissionResolver resolver = filter.getActionPermissionResolver(); assertNotNull(resolver); assertTrue(resolver instanceof DestinationActionPermissionResolver); }
public static <T extends NamedConfig> T getConfig(ConfigPatternMatcher configPatternMatcher, Map<String, T> configs, String name, Class clazz) { return getConfig(configPatternMatcher, configs, name, clazz...
@Test public void getExistingConfig() { QueueConfig aDefault = new QueueConfig("newConfig"); aDefault.setBackupCount(5); queueConfigs.put(aDefault.getName(), aDefault); QueueConfig newConfig = ConfigUtils.getConfig(configPatternMatcher, queueConfigs, "newConfig", QueueConfig.class); ...
@Override public Mono<Authentication> convert(ServerWebExchange exchange) { return super.convert(exchange) // validate the password .<Authentication>flatMap(token -> { var credentials = (String) token.getCredentials(); byte[] credentialsBytes; ...
@Test void applyUsernameAndInvalidPasswordThenBadCredentialsException() { var username = "username"; var password = "password"; formData.add("username", username); formData.add("password", Base64.getEncoder().encodeToString(password.getBytes())); when(cryptoService.decrypt(...