From cb2965a69753ac686923eb2634fe4151c02700f4 Mon Sep 17 00:00:00 2001 From: Matteo Merli Date: Sat, 28 Mar 2026 10:34:37 -0700 Subject: [PATCH 1/4] [improve][test] Fix rawtypes compile warnings in test code MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add proper generic type parameters to raw types across test code: - ArrayList/HashSet/HashMap → diamond operator <> - Class → Class - Producer/Consumer/Message/Schema → proper type params - ProducerBuilder/ConsumerBuilder/ReaderBuilder → - Record/PulsarSink/MessageImpl → proper type params - CompletableFuture/Answer/BiConsumer → proper type params - Use method-level @SuppressWarnings("rawtypes") only where fixing would cascade into compile errors --- .../InflightReadsLimiterIntegrationTest.java | 4 +- .../mledger/impl/ManagedCursorTest.java | 6 +- .../mledger/impl/ManagedLedgerBkTest.java | 14 +-- .../mledger/impl/ManagedLedgerTest.java | 12 +-- .../mledger/impl/OffloadPrefixReadTest.java | 6 +- .../MangedLedgerInterceptorImpl2Test.java | 4 +- ...ntryCacheKeySharedSubscriptionV30Test.java | 5 +- .../pulsar/PulsarBrokerStarterTest.java | 2 +- .../PulsarClusterMetadataTeardownTest.java | 2 +- .../pulsar/PulsarVersionStarterTest.java | 2 +- .../LedgerLostAndSkipNonRecoverableTest.java | 11 ++- .../pulsar/broker/admin/AdminApi2Test.java | 16 ++-- .../broker/admin/AdminApiHealthCheckTest.java | 1 + .../admin/AdminApiMaxUnackedMessagesTest.java | 12 +-- .../broker/admin/AdminApiSchemaTest.java | 2 +- .../AdminApiSchemaValidationEnforcedTest.java | 8 +- .../apache/pulsar/broker/admin/AdminTest.java | 4 +- .../admin/AnalyzeBacklogSubscriptionTest.java | 14 +-- .../broker/admin/CreateSubscriptionTest.java | 8 +- .../broker/admin/TopicMessageTTLTest.java | 2 +- .../broker/admin/TopicPoliciesTest.java | 38 ++++---- .../admin/v3/AdminApiTransactionTest.java | 2 +- .../auth/MockedPulsarServiceBaseTest.java | 4 +- .../BrokerEntryCacheRollingRestartTest.java | 1 + .../broker/cache/BrokerEntryCacheTest.java | 4 + .../MinimumBacklogCacheStrategyTest.java | 1 + .../ExceptionsBrokerInterceptorTest.java | 4 +- .../ModularLoadManagerStrategyTest.java | 8 +- .../ExtensibleLoadManagerImplTest.java | 2 + .../channel/ServiceUnitStateChannelTest.java | 8 +- .../extensions/models/TopKBundlesTest.java | 6 +- .../reporter/BrokerLoadDataReporterTest.java | 1 + .../TopBundleLoadDataReporterTest.java | 3 +- .../scheduler/SplitSchedulerTest.java | 4 +- ...faultNamespaceBundleSplitStrategyTest.java | 2 +- .../impl/ModularLoadManagerImplTest.java | 4 +- .../broker/service/OneWayReplicatorTest.java | 10 +- .../broker/service/PersistentTopicTest.java | 2 +- .../service/ReplicatedSubscriptionTest.java | 4 +- .../pulsar/broker/service/TopicGCTest.java | 2 +- ...ransactionalReplicateSubscriptionTest.java | 4 +- .../PersistentReplicatorInflightTaskTest.java | 2 +- .../PersistentTopicProtectedMethodsTest.java | 2 +- .../persistent/PersistentTopicTest.java | 8 +- .../systopic/PartitionedSystemTopicTest.java | 6 +- .../pulsar/broker/tools/BrokerToolTest.java | 2 +- .../SegmentAbortedTxnProcessorTest.java | 7 +- .../TopicTransactionBufferRecoverTest.java | 8 +- .../transaction/TransactionConsumeTest.java | 2 +- .../broker/transaction/TransactionTest.java | 19 +++- .../impl/MLPendingAckStoreTest.java | 2 +- ...dditionalServletWithPulsarServiceTest.java | 1 + .../client/api/ProducerConsumerBase.java | 2 +- .../pulsar/admin/cli/PulsarAdminToolTest.java | 3 +- .../cli/PulsarClientToolForceBatchNum.java | 1 + .../impl/BatchMessageContainerImplTest.java | 2 +- .../pulsar/client/impl/BuildersTest.java | 4 +- .../pulsar/client/impl/ClientCnxTest.java | 4 +- .../pulsar/client/impl/ConsumerImplTest.java | 3 + .../pulsar/client/impl/MessageImplTest.java | 18 ++-- .../impl/MultiTopicsConsumerImplTest.java | 2 + .../impl/PartitionedProducerImplTest.java | 23 +++-- .../impl/PatternConsumerUpdateQueueTest.java | 7 +- .../client/impl/TableViewBuilderImplTest.java | 12 +-- .../pulsar/client/impl/TableViewImplTest.java | 2 +- .../impl/TypedMessageBuilderImplTest.java | 49 ++++++---- .../impl/conf/ConfigurationDataUtilsTest.java | 6 +- .../impl/schema/KeyValueSchemaInfoTest.java | 4 +- .../impl/schema/KeyValueSchemaTest.java | 10 +- .../impl/schema/PrimitiveSchemaTest.java | 11 ++- .../client/impl/schema/SchemaBuilderTest.java | 3 +- .../SupportVersioningAvroSchemaTest.java | 2 +- .../SupportVersioningKeyValueSchemaTest.java | 8 +- .../schema/generic/GenericAvroReaderTest.java | 4 + .../GenericProtobufNativeReaderTest.java | 2 +- .../AsyncDualMemoryLimiterUtilTest.java | 11 ++- .../semaphore/AsyncSemaphoreImplTest.java | 2 +- .../functions/instance/ContextImplTest.java | 7 +- .../instance/JavaInstanceRunnableTest.java | 8 +- .../instance/ProducerBuilderFactoryTest.java | 2 +- .../functions/instance/ProducerCacheTest.java | 8 +- .../functions/instance/SinkRecordTest.java | 3 +- .../instance/state/BKStateStoreImplTest.java | 1 + .../pulsar/functions/sink/PulsarSinkTest.java | 58 ++++++------ .../source/PulsarFunctionRecordTest.java | 4 +- .../windowing/WindowFunctionExecutorTest.java | 3 + .../windowing/WindowManagerTest.java | 93 ++++++++++--------- .../kubernetes/KubernetesRuntimeTest.java | 2 +- .../worker/FunctionMetaDataManagerTest.java | 3 + .../worker/FunctionWorkerStarterTest.java | 2 +- .../functions/worker/LeaderServiceTest.java | 7 +- .../worker/SchedulerManagerTest.java | 1 + .../functions/worker/WorkerUtilsTest.java | 1 + .../api/v3/AbstractFunctionsResourceTest.java | 5 +- .../BookKeeperClusterTestCase.java | 2 +- .../metadata/DualMetadataCacheTest.java | 2 +- .../pulsar/metadata/MetadataCacheTest.java | 2 +- .../apache/pulsar/metadata/TestZKServer.java | 2 +- .../impl/TxnLogBufferedWriterTest.java | 15 +-- 99 files changed, 405 insertions(+), 329 deletions(-) diff --git a/managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/InflightReadsLimiterIntegrationTest.java b/managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/InflightReadsLimiterIntegrationTest.java index 01a8808a2b96c..c62bd8231bb13 100644 --- a/managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/InflightReadsLimiterIntegrationTest.java +++ b/managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/InflightReadsLimiterIntegrationTest.java @@ -102,7 +102,7 @@ public void testPreciseLimitation(String missingCase) throws Exception { LedgerHandle currentLedger = ml.currentLedger; LedgerHandle spyCurrentLedger = Mockito.spy(currentLedger); ml.currentLedger = spyCurrentLedger; - Answer answer = invocation -> { + Answer answer = invocation -> { long firstEntry = (long) invocation.getArguments()[0]; log.info("reading entry: {}", firstEntry); if (firstEntry == start1) { @@ -112,7 +112,7 @@ public void testPreciseLimitation(String missingCase) throws Exception { Object res = invocation.callRealMethod(); return res; } else if (secondReadEntries.contains(firstEntry)) { - final CompletableFuture res = new CompletableFuture<>(); + final CompletableFuture res = new CompletableFuture<>(); threadFactory.newThread(() -> { try { readCompleteSignal2.await(); diff --git a/managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/ManagedCursorTest.java b/managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/ManagedCursorTest.java index a3449298fd89c..8b2c632a70f1a 100644 --- a/managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/ManagedCursorTest.java +++ b/managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/ManagedCursorTest.java @@ -1077,7 +1077,7 @@ void testConcurrentResetCursor() throws Exception { final int messages = 100; final int consumers = 5; - List> futures = new ArrayList(); + List> futures = new ArrayList<>(); @Cleanup("shutdownNow") ExecutorService executor = Executors.newCachedThreadPool(); final CyclicBarrier barrier = new CyclicBarrier(consumers + 1); @@ -2372,7 +2372,7 @@ void testReadEntriesOrWaitBlocking() throws Exception { final int messages = 100; final int consumers = 10; - List> futures = new ArrayList(); + List> futures = new ArrayList<>(); @Cleanup("shutdownNow") ExecutorService executor = Executors.newCachedThreadPool(); final CyclicBarrier barrier = new CyclicBarrier(consumers + 1); @@ -3115,7 +3115,7 @@ void testReplayEntries() throws Exception { ledger.addEntry("entry4".getBytes(Encoding)); // 1. Replay empty position set should return empty entry set - Set positions = new HashSet(); + Set positions = new HashSet<>(); assertTrue(c1.replayEntries(positions).isEmpty()); positions.add(p1); diff --git a/managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/ManagedLedgerBkTest.java b/managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/ManagedLedgerBkTest.java index ee6a9c78658e7..6865bf1bbe2ce 100644 --- a/managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/ManagedLedgerBkTest.java +++ b/managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/ManagedLedgerBkTest.java @@ -187,7 +187,7 @@ public void verifyConcurrentUsage() throws Exception { final AtomicBoolean done = new AtomicBoolean(); final CyclicBarrier barrier = new CyclicBarrier(numProducers + numConsumers + 1); - List> futures = new ArrayList(); + List> futures = new ArrayList<>(); for (int i = 0; i < numProducers; i++) { futures.add(executor.submit(() -> { @@ -266,7 +266,7 @@ public void verifyAsyncReadEntryUsingCache() throws Exception { final AtomicBoolean done = new AtomicBoolean(); final CyclicBarrier barrier = new CyclicBarrier(numProducers + numConsumers + 1); - List> futures = new ArrayList(); + List> futures = new ArrayList<>(); List positions = new CopyOnWriteArrayList<>(); for (int i = 0; i < numProducers; i++) { @@ -375,12 +375,12 @@ public void testConcurrentMarkDelete() throws Exception { mlConfig.setMetadataMaxEntriesPerLedger(10); ManagedLedger ledger = factory.open("ml-markdelete-ledger", mlConfig); - final List addedEntries = new ArrayList(); + final List addedEntries = new ArrayList<>(); int numCursors = 10; final CyclicBarrier barrier = new CyclicBarrier(numCursors); - List cursors = new ArrayList(); + List cursors = new ArrayList<>(); for (int i = 0; i < numCursors; i++) { cursors.add(ledger.openCursor(String.format("c%d", i))); } @@ -390,7 +390,7 @@ public void testConcurrentMarkDelete() throws Exception { addedEntries.add(pos); } - List> futures = new ArrayList(); + List> futures = new ArrayList<>(); for (ManagedCursor cursor : cursors) { futures.add(executor.submit(() -> { @@ -424,7 +424,7 @@ public void asyncMarkDeleteAndClose() throws Exception { ManagedLedger ledger = factory.open("my_test_ledger" + testName, config); ManagedCursor cursor = ledger.openCursor("c1"); - List positions = new ArrayList(); + List positions = new ArrayList<>(); for (int i = 0; i < 10; i++) { Position p = ledger.addEntry("entry".getBytes()); @@ -432,7 +432,7 @@ public void asyncMarkDeleteAndClose() throws Exception { } final CountDownLatch counter = new CountDownLatch(positions.size()); - final AtomicReference gotException = new AtomicReference(); + final AtomicReference gotException = new AtomicReference<>(); for (Position p : positions) { cursor.asyncDelete(p, new DeleteCallback() { diff --git a/managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/ManagedLedgerTest.java b/managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/ManagedLedgerTest.java index 353768a964ebc..cf6872d4e8a65 100644 --- a/managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/ManagedLedgerTest.java +++ b/managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/ManagedLedgerTest.java @@ -1493,7 +1493,7 @@ public void getCursors() throws Exception { c2.close(); ledger.deleteCursor("c2"); - assertEquals(Sets.newHashSet(ledger.getCursors()), new HashSet()); + assertEquals(Sets.newHashSet(ledger.getCursors()), new HashSet<>()); } @Test @@ -1621,7 +1621,7 @@ public void updatePropertiesFailed(ManagedLedgerException exception, Object ctx) public void ledgersList() throws Exception { MetaStore store = factory.getMetaStore(); - assertEquals(Sets.newHashSet(store.getManagedLedgers()), new HashSet()); + assertEquals(Sets.newHashSet(store.getManagedLedgers()), new HashSet<>()); ManagedLedger ledger1 = factory.open("ledger1"); assertEquals(Sets.newHashSet(store.getManagedLedgers()), Sets.newHashSet("ledger1")); ManagedLedger ledger2 = factory.open("ledger2"); @@ -1629,7 +1629,7 @@ public void ledgersList() throws Exception { ledger1.delete(); assertEquals(Sets.newHashSet(store.getManagedLedgers()), Sets.newHashSet("ledger2")); ledger2.delete(); - assertEquals(Sets.newHashSet(store.getManagedLedgers()), new HashSet()); + assertEquals(Sets.newHashSet(store.getManagedLedgers()), new HashSet<>()); } @Test @@ -3225,7 +3225,7 @@ public void testManagedLedgerWithCreateLedgerTimeOut() throws Exception { latch.await(config.getMetadataOperationsTimeoutSeconds() + 2, TimeUnit.SECONDS); assertEquals(response.get(), BKException.Code.TimeoutException); assertTrue(ctxHolder.get() instanceof CompletableFuture); - CompletableFuture ledgerCreateHook = (CompletableFuture) ctxHolder.get(); + CompletableFuture ledgerCreateHook = (CompletableFuture) ctxHolder.get(); assertTrue(ledgerCreateHook.isCompletedExceptionally()); ledger.close(); @@ -3650,7 +3650,7 @@ public void testManagedLedgerWithPlacementPolicyInCustomMetadata() throws Except assertEquals(config.getProperties().get("key"), "value"); } - private void setFieldValue(Class clazz, Object classObj, String fieldName, Object fieldValue) throws Exception { + private void setFieldValue(Class clazz, Object classObj, String fieldName, Object fieldValue) throws Exception { Field field = clazz.getDeclaredField(fieldName); field.setAccessible(true); field.set(classObj, fieldValue); @@ -4530,7 +4530,7 @@ private long calculatePendingTaskCount(OrderedScheduler orderedScheduler) { BlockingQueue queue = WhiteboxImpl.getInternalState(boundedScheduledExecutorService, "queue"); for (Runnable r : queue) { if (r instanceof FutureTask) { - FutureTask futureTask = (FutureTask) r; + FutureTask futureTask = (FutureTask) r; if (!futureTask.isCancelled() && !futureTask.isDone()) { taskCounter++; } diff --git a/managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/OffloadPrefixReadTest.java b/managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/OffloadPrefixReadTest.java index 00ee5b7573916..2c6bfba305b47 100644 --- a/managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/OffloadPrefixReadTest.java +++ b/managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/OffloadPrefixReadTest.java @@ -254,7 +254,7 @@ public void testBookkeeperFirstOffloadRead(String offloadType) throws Exception } config.setRetentionTime(0, TimeUnit.MILLISECONDS); config.setRetentionSizeInMB(0); - CompletableFuture trimFuture = new CompletableFuture(); + CompletableFuture trimFuture = new CompletableFuture<>(); ledger.trimConsumedLedgersInBackground(trimFuture); trimFuture.join(); Awaitility.await().untilAsserted(() -> { @@ -381,7 +381,7 @@ public CompletableFuture closeAsync() { static class MockOffloadReadHandle implements ReadHandle, OffloadedLedgerHandle { final long id; - final List entries = new ArrayList(); + final List entries = new ArrayList<>(); final LedgerMetadata metadata; long lastAccessTimestamp = System.currentTimeMillis(); @@ -413,7 +413,7 @@ public CompletableFuture closeAsync() { @Override public CompletableFuture readAsync(long firstEntry, long lastEntry) { - List readEntries = new ArrayList(); + List readEntries = new ArrayList<>(); for (long eid = firstEntry; eid <= lastEntry; eid++) { ByteBuf buf = entries.get((int) eid).retainedSlice(); readEntries.add(LedgerEntryImpl.create(id, eid, buf.readableBytes(), buf)); diff --git a/pulsar-broker/src/test/java/org/apache/bookkeeper/mledger/impl/MangedLedgerInterceptorImpl2Test.java b/pulsar-broker/src/test/java/org/apache/bookkeeper/mledger/impl/MangedLedgerInterceptorImpl2Test.java index 0a7effc9988cf..694c480ea7746 100644 --- a/pulsar-broker/src/test/java/org/apache/bookkeeper/mledger/impl/MangedLedgerInterceptorImpl2Test.java +++ b/pulsar-broker/src/test/java/org/apache/bookkeeper/mledger/impl/MangedLedgerInterceptorImpl2Test.java @@ -57,9 +57,9 @@ public void testCurrentLedgerSizeCorrectIfHasInterceptor() throws Exception { // Registry interceptor. ManagedLedgerConfig config = new ManagedLedgerConfig(); - Set processors = new HashSet(); + Set processors = new HashSet<>(); processors.add(new TestPayloadProcessor()); - ManagedLedgerInterceptor interceptor = new ManagedLedgerInterceptorImpl(new HashSet(), processors); + ManagedLedgerInterceptor interceptor = new ManagedLedgerInterceptorImpl(new HashSet<>(), processors); config.setManagedLedgerInterceptor(interceptor); config.setMaxEntriesPerLedger(100); diff --git a/pulsar-broker/src/test/java/org/apache/bookkeeper/mledger/impl/NonEntryCacheKeySharedSubscriptionV30Test.java b/pulsar-broker/src/test/java/org/apache/bookkeeper/mledger/impl/NonEntryCacheKeySharedSubscriptionV30Test.java index 734d280684080..48fb4557b26c2 100644 --- a/pulsar-broker/src/test/java/org/apache/bookkeeper/mledger/impl/NonEntryCacheKeySharedSubscriptionV30Test.java +++ b/pulsar-broker/src/test/java/org/apache/bookkeeper/mledger/impl/NonEntryCacheKeySharedSubscriptionV30Test.java @@ -149,11 +149,11 @@ public void testRecentJoinQueueIsInOrderAfterRewind() throws Exception { LedgerHandle spyFirstLedger = spy(firstLedger); CountDownLatch replyReadSignal = new CountDownLatch(1); AtomicBoolean replayReadWasTriggered = new AtomicBoolean(); - Answer answer = invocation -> { + Answer answer = invocation -> { long firstEntry = (long) invocation.getArguments()[0]; if (firstEntry == firstWaitingAckPos.getEntryId()) { replayReadWasTriggered.set(true); - final CompletableFuture res = new CompletableFuture<>(); + final CompletableFuture res = new CompletableFuture<>(); threadFactory.newThread(() -> { try { replyReadSignal.await(); @@ -246,6 +246,7 @@ public void testRecentJoinQueueIsInOrderAfterRewind() throws Exception { consumerList.get(consumerList.size() - 1).join(); synchronized (dispatcher) { + @SuppressWarnings("rawtypes") LinkedHashMap recentJoinedConsumers = dispatcher.getRecentlyJoinedConsumers(); assertTrue(verifyMapItemsAreInOrder(recentJoinedConsumers)); } diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/PulsarBrokerStarterTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/PulsarBrokerStarterTest.java index 7501d5585095e..1875e5a0d9cd7 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/PulsarBrokerStarterTest.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/PulsarBrokerStarterTest.java @@ -375,7 +375,7 @@ public void testMainGenerateDocs() throws Exception { ByteArrayOutputStream baoStream = new ByteArrayOutputStream(); System.setOut(new PrintStream(baoStream)); - Class argumentsClass = Class.forName("org.apache.pulsar.PulsarBrokerStarter$StarterArguments"); + Class argumentsClass = Class.forName("org.apache.pulsar.PulsarBrokerStarter$StarterArguments"); PulsarBrokerStarter.main(new String[]{"-g"}); String message = baoStream.toString(); diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/PulsarClusterMetadataTeardownTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/PulsarClusterMetadataTeardownTest.java index 95d12f378c55f..ebde19f62931f 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/PulsarClusterMetadataTeardownTest.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/PulsarClusterMetadataTeardownTest.java @@ -34,7 +34,7 @@ public void testMainGenerateDocs() throws Exception { ByteArrayOutputStream baoStream = new ByteArrayOutputStream(); System.setOut(new PrintStream(baoStream)); - Class argumentsClass = + Class argumentsClass = Class.forName("org.apache.pulsar.PulsarClusterMetadataTeardown$Arguments"); PulsarClusterMetadataTeardown.main(new String[]{"-zk", "zk", "-g"}); diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/PulsarVersionStarterTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/PulsarVersionStarterTest.java index b921c3d384315..0ccb698c4624d 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/PulsarVersionStarterTest.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/PulsarVersionStarterTest.java @@ -34,7 +34,7 @@ public void testMainGenerateDocs() throws Exception { ByteArrayOutputStream baoStream = new ByteArrayOutputStream(); System.setOut(new PrintStream(baoStream)); - Class argumentsClass = + Class argumentsClass = Class.forName("org.apache.pulsar.PulsarVersionStarter$Arguments"); PulsarVersionStarter.main(new String[]{"-g"}); diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/LedgerLostAndSkipNonRecoverableTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/LedgerLostAndSkipNonRecoverableTest.java index 8d79a49b4c749..ba27ccf262bf6 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/LedgerLostAndSkipNonRecoverableTest.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/LedgerLostAndSkipNonRecoverableTest.java @@ -92,7 +92,7 @@ public void testMarkDeletedPositionCanForwardAfterTopicLedgerLost(boolean enable ConsumerAndReceivedMessages consumerAndReceivedMessages1 = waitConsumeAndAllMessages(topicName, subName, enabledBatch, false); List[] messageIds = consumerAndReceivedMessages1.messageIds; - Consumer consumer = consumerAndReceivedMessages1.consumer; + Consumer consumer = consumerAndReceivedMessages1.consumer; MessageIdImpl individualPosition = messageIds[1].get(messageCountPerEntry - 1); MessageIdImpl expectedMarkDeletedPosition = new MessageIdImpl(messageIds[0].get(0).getLedgerId(), messageIds[0].get(0).getEntryId(), -1); @@ -153,7 +153,7 @@ private void waitPersistentCursorLedger(String topicName, String subName, final private List[] sendManyMessages(String topicName, int ledgerCount, int messageCountPerLedger, int messageCountPerEntry) throws Exception { - List[] messageIds = new List[ledgerCount]; + @SuppressWarnings({"unchecked", "rawtypes"}) List[] messageIds = new List[ledgerCount]; for (int i = 0; i < ledgerCount; i++){ admin.topics().unload(topicName); if (messageCountPerEntry == 1) { @@ -221,9 +221,9 @@ private ConsumerAndReceivedMessages waitConsumeAndAllMessages(String topicName, final boolean enabledBatch, boolean ack) throws Exception { List messageIds = new ArrayList<>(); - final Consumer consumer = createConsumer(topicName, subName, enabledBatch); + final Consumer consumer = createConsumer(topicName, subName, enabledBatch); while (true){ - Message message = consumer.receive(5, TimeUnit.SECONDS); + Message message = consumer.receive(5, TimeUnit.SECONDS); if (message != null){ messageIds.add((MessageIdImpl) message.getMessageId()); if (ack) { @@ -239,13 +239,14 @@ private ConsumerAndReceivedMessages waitConsumeAndAllMessages(String topicName, @AllArgsConstructor private static class ConsumerAndReceivedMessages { - private Consumer consumer; + private Consumer consumer; private List[] messageIds; } private List[] sortMessageId(List messageIds, boolean enabledBatch){ Map> map = messageIds.stream().collect(Collectors.groupingBy(v -> v.getLedgerId())); TreeMap> sortedMap = new TreeMap<>(map); + @SuppressWarnings({"unchecked", "rawtypes"}) List[] res = new List[sortedMap.size()]; Iterator>> iterator = sortedMap.entrySet().iterator(); for (int i = 0; i < sortedMap.size(); i++){ diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/AdminApi2Test.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/AdminApi2Test.java index a2aa358cc0088..9220b706d9576 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/AdminApi2Test.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/AdminApi2Test.java @@ -2623,7 +2623,7 @@ public void testMaxSubscriptionsPerTopic() throws Exception { final String topic = "persistent://testTenant/ns1/max-subscriptions-per-topic"; admin.topics().createPartitionedTopic(topic, 3); - Producer producer = pulsarClient.newProducer().topic(topic).create(); + Producer producer = pulsarClient.newProducer().topic(topic).create(); producer.close(); // create subscription @@ -2662,9 +2662,9 @@ public void testMaxSubscriptionsPerTopic() throws Exception { producer = pulsarClient.newProducer().topic(topic).create(); producer.close(); - Consumer consumer1 = null; - Consumer consumer2 = null; - Consumer consumer3 = null; + Consumer consumer1 = null; + Consumer consumer2 = null; + Consumer consumer3 = null; try { consumer1 = pulsarClient.newConsumer().subscriptionName("test-sub1").topic(topic).subscribe(); @@ -3268,14 +3268,14 @@ private AtomicInteger injectSchemaCheckCounterForTopic(String topicName) { AbstractTopic topic = (AbstractTopic) topics.get(topicName).join().get(); AbstractTopic spyTopic = Mockito.spy(topic); AtomicInteger counter = new AtomicInteger(); - doAnswer(new Answer() { + doAnswer(new Answer() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { counter.incrementAndGet(); return invocation.callRealMethod(); } }).when(spyTopic).addSchema(any(SchemaData.class)); - doAnswer(new Answer() { + doAnswer(new Answer() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { counter.incrementAndGet(); @@ -3797,7 +3797,7 @@ private void testAnalyzeSubscriptionBacklogNotCauseStuck() throws Exception { admin.topics().analyzeSubscriptionBacklog(topic, subscription, Optional.of(MessageIdImpl.earliest)); for (int i = 0; i < 10; i++) { Awaitility.await().untilAsserted(() -> { - Message m = consumer.receive(); + Message m = consumer.receive(); assertNotNull(m); consumer.acknowledge(m); }); @@ -4162,7 +4162,7 @@ public void testOverridesNamespaceOffloadThreshold() throws Exception { public void testDeletePatchyPartitionedTopic() throws Exception { final String topic = BrokerTestUtil.newUniqueName(defaultNamespace + "/tp"); admin.topics().createPartitionedTopic(topic, 2); - Producer producer = pulsarClient.newProducer().topic(TopicName.get(topic).getPartition(0).toString()) + Producer producer = pulsarClient.newProducer().topic(TopicName.get(topic).getPartition(0).toString()) .create(); // Mock a scenario that "-partition-1" has been removed due to topic GC. pulsar.getBrokerService().getTopic(TopicName.get(topic).getPartition(1).toString(), false) diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/AdminApiHealthCheckTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/AdminApiHealthCheckTest.java index 25c8f1e716771..961f2fd903e72 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/AdminApiHealthCheckTest.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/AdminApiHealthCheckTest.java @@ -190,6 +190,7 @@ public void testDeadlockDetectionOverhead() { class DummyProducerBuilder extends ProducerBuilderImpl { // This is a dummy producer builder to test the health check timeout // the producer constructed by this builder will not send any message + @SuppressWarnings("rawtypes") public DummyProducerBuilder(PulsarClientImpl client, Schema schema) { super(client, schema); } diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/AdminApiMaxUnackedMessagesTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/AdminApiMaxUnackedMessagesTest.java index 1a0d4fa75b814..d2ec8cd48e3ef 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/AdminApiMaxUnackedMessagesTest.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/AdminApiMaxUnackedMessagesTest.java @@ -162,7 +162,7 @@ public void testMaxUnackedMessagesPerConsumerPriority() throws Exception { org.apache.pulsar.broker.service.Consumer serverConsumer = persistentTopic.getSubscription("sub").getConsumers().get(0); assertEquals(serverConsumer.getMaxUnackedMessages(), topicLevelPolicy); - List msgs = consumeMsg(consumer, 3); + List> msgs = consumeMsg(consumer, 3); assertEquals(msgs.size(), 1); //disable topic-level limiter admin.topics().setMaxUnackedMessagesOnConsumer(topic, 0); @@ -196,10 +196,10 @@ public void testMaxUnackedMessagesPerConsumerPriority() throws Exception { } - private List consumeMsg(Consumer consumer, int msgNum) throws Exception { - List list = new ArrayList<>(); + private List> consumeMsg(Consumer consumer, int msgNum) throws Exception { + List> list = new ArrayList<>(); for (int i = 0; i < msgNum; i++) { - Message message = consumer.receive(1500, TimeUnit.MILLISECONDS); + Message message = consumer.receive(1500, TimeUnit.MILLISECONDS); if (message == null) { break; } @@ -208,8 +208,8 @@ private List consumeMsg(Consumer consumer, int msgNum) throws Except return list; } - private void ackMsgs(Consumer consumer, List msgs) throws Exception { - for (Message msg : msgs) { + private void ackMsgs(Consumer consumer, List> msgs) throws Exception { + for (Message msg : msgs) { consumer.acknowledge(msg); } } diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/AdminApiSchemaTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/AdminApiSchemaTest.java index 034194bea0f8c..e12ea6cc39448 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/AdminApiSchemaTest.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/AdminApiSchemaTest.java @@ -250,7 +250,7 @@ public void createKeyValueSchema(ApiVersion version) throws Exception { String namespace = format("%s%s%s", "schematest", "/", "test"); String topicName = "persistent://" + namespace + "/test-key-value-schema"; - Schema keyValueSchema = Schema.KeyValue(Schema.AVRO(Foo.class), Schema.AVRO(Foo.class)); + Schema keyValueSchema = Schema.KeyValue(Schema.AVRO(Foo.class), Schema.AVRO(Foo.class)); admin.schemas().createSchema(topicName, keyValueSchema.getSchemaInfo()); SchemaInfo schemaInfo = admin.schemas().getSchemaInfo(topicName); diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/AdminApiSchemaValidationEnforcedTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/AdminApiSchemaValidationEnforcedTest.java index 5c7f81892b1bf..2d5eb9bed2f40 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/AdminApiSchemaValidationEnforcedTest.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/AdminApiSchemaValidationEnforcedTest.java @@ -82,7 +82,7 @@ public void testDisableSchemaValidationEnforcedNoSchema() throws Exception { } catch (PulsarAdminException.NotFoundException e) { assertEquals(e.getMessage(), "Schema not found"); } - try (Producer p = pulsarClient.newProducer().topic(topicName).create()) { + try (Producer p = pulsarClient.newProducer().topic(topicName).create()) { p.send("test schemaValidationEnforced".getBytes()); } } @@ -110,7 +110,7 @@ public void testDisableSchemaValidationEnforcedHasSchema() throws Exception { .build(); PostSchemaPayload postSchemaPayload = new PostSchemaPayload("STRING", "", properties); admin.schemas().createSchema(topicName, postSchemaPayload); - try (Producer p = pulsarClient.newProducer().topic(topicName).create()) { + try (Producer p = pulsarClient.newProducer().topic(topicName).create()) { p.send("test schemaValidationEnforced".getBytes()); } assertSchemaInfoEquals(admin.schemas().getSchemaInfo(topicName), schemaInfo); @@ -138,7 +138,7 @@ public void testEnableSchemaValidationEnforcedNoSchema() throws Exception { } catch (PulsarAdminException.NotFoundException e) { assertEquals(e.getMessage(), "Schema not found"); } - try (Producer p = pulsarClient.newProducer().topic(topicName).create()) { + try (Producer p = pulsarClient.newProducer().topic(topicName).create()) { p.send("test schemaValidationEnforced".getBytes()); } } @@ -169,7 +169,7 @@ public void testEnableSchemaValidationEnforcedHasSchemaMismatch() throws Excepti .build(); PostSchemaPayload postSchemaPayload = new PostSchemaPayload("STRING", "", properties); admin.schemas().createSchema(topicName, postSchemaPayload); - try (Producer p = pulsarClient.newProducer().topic(topicName).create()) { + try (Producer p = pulsarClient.newProducer().topic(topicName).create()) { fail("Client no schema, but topic has schema, should fail"); } catch (PulsarClientException e) { assertTrue(e.getMessage().contains("IncompatibleSchemaException")); diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/AdminTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/AdminTest.java index 88759522e6cb0..4b8791b9093a2 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/AdminTest.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/AdminTest.java @@ -355,7 +355,7 @@ public void clusters() throws Exception { // clear caches to load data from metadata-store again MetadataCacheImpl clusterCache = (MetadataCacheImpl) pulsar.getPulsarResources() .getClusterResources().getCache(); - MetadataCacheImpl isolationPolicyCache = (MetadataCacheImpl) pulsar.getPulsarResources() + MetadataCacheImpl isolationPolicyCache = (MetadataCacheImpl) pulsar.getPulsarResources() .getNamespaceResources().getIsolationPolicies().getCache(); AbstractMetadataStore store = (AbstractMetadataStore) clusterCache.getStore(); clusterCache.invalidateAll(); @@ -962,7 +962,7 @@ public void test500Error() throws Exception { AsyncResponse response1 = mock(AsyncResponse.class); ArgumentCaptor responseCaptor = ArgumentCaptor.forClass(RestException.class); - CompletableFuture> future = new CompletableFuture(); + CompletableFuture> future = new CompletableFuture<>(); future.completeExceptionally(new RuntimeException("500 error contains error message")); NamespaceService namespaceService = pulsar.getNamespaceService(); diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/AnalyzeBacklogSubscriptionTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/AnalyzeBacklogSubscriptionTest.java index 8b3f190b5da67..34753579c3f0d 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/AnalyzeBacklogSubscriptionTest.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/AnalyzeBacklogSubscriptionTest.java @@ -105,7 +105,7 @@ private void simpleAnalyzeBacklogTest(boolean batching) throws Exception { verifyBacklog(topic, "from-middle", numEntries / 2, numMessages / 2); - try (Consumer consumer = pulsarClient + try (Consumer consumer = pulsarClient .newConsumer() .topic(topic) // we want to wait for the server to process acks, in order to not have a flaky test @@ -113,11 +113,11 @@ private void simpleAnalyzeBacklogTest(boolean batching) throws Exception { .subscriptionName(subName) .subscriptionType(SubscriptionType.Shared) .subscribe()) { - Message receive1 = consumer.receive(); - Message receive2 = consumer.receive(); - Message receive3 = consumer.receive(); - Message receive4 = consumer.receive(); - Message receive5 = consumer.receive(); + Message receive1 = consumer.receive(); + Message receive2 = consumer.receive(); + Message receive3 = consumer.receive(); + Message receive4 = consumer.receive(); + Message receive5 = consumer.receive(); verifyBacklog(topic, subName, numEntries, numMessages); @@ -141,7 +141,7 @@ private void simpleAnalyzeBacklogTest(boolean batching) throws Exception { int count = numMessages - 5; while (count-- > 0) { - Message m = consumer.receive(); + Message m = consumer.receive(); consumer.acknowledge(m); } diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/CreateSubscriptionTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/CreateSubscriptionTest.java index 282eabd345809..7d1640a1716e7 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/CreateSubscriptionTest.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/CreateSubscriptionTest.java @@ -206,7 +206,7 @@ public void addSubscriptionPropertiesTest(SubscriptionMode subscriptionMode) thr for (int i = 0; i < 10; i++) { producer.send("msg".getBytes(StandardCharsets.UTF_8)); } - Message message = consumer.receive(1, TimeUnit.SECONDS); + Message message = consumer.receive(1, TimeUnit.SECONDS); assertNotNull(message); consumer.acknowledge(message); MessageIdImpl messageId = (MessageIdImpl) message.getMessageId(); @@ -319,7 +319,7 @@ public void addSubscriptionPropertiesTest(SubscriptionMode subscriptionMode) thr Map mapShared = new HashMap<>(); mapShared.put("6", "7"); // open two consumers with a Shared Subscription - Consumer consumerShared1 = pulsarClient.newConsumer().topic(topic).receiverQueueSize(1) + Consumer consumerShared1 = pulsarClient.newConsumer().topic(topic).receiverQueueSize(1) .subscriptionMode(subscriptionMode) .subscriptionType(SubscriptionType.Shared) .subscriptionProperties(mapShared) @@ -332,7 +332,7 @@ public void addSubscriptionPropertiesTest(SubscriptionMode subscriptionMode) thr // add a new consumer, the properties are not updated Map mapShared2 = new HashMap<>(); mapShared2.put("8", "9"); - Consumer consumerShared2 = pulsarClient.newConsumer().topic(topic).receiverQueueSize(1) + Consumer consumerShared2 = pulsarClient.newConsumer().topic(topic).receiverQueueSize(1) .subscriptionMode(subscriptionMode) .subscriptionType(SubscriptionType.Shared) .subscriptionProperties(mapShared2) @@ -344,7 +344,7 @@ public void addSubscriptionPropertiesTest(SubscriptionMode subscriptionMode) thr // add a third consumer, the properties are NOT updated Map mapShared3 = new HashMap<>(); mapShared3.put("10", "11"); - Consumer consumerShared3 = pulsarClient.newConsumer().topic(topic).receiverQueueSize(1) + Consumer consumerShared3 = pulsarClient.newConsumer().topic(topic).receiverQueueSize(1) .subscriptionMode(subscriptionMode) .subscriptionType(SubscriptionType.Shared) .subscriptionProperties(mapShared3) diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/TopicMessageTTLTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/TopicMessageTTLTest.java index 8ecd37a931d0f..ca702ec89e7c6 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/TopicMessageTTLTest.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/TopicMessageTTLTest.java @@ -56,7 +56,7 @@ protected void setup() throws Exception { admin.tenants().createTenant(this.testTenant, tenantInfo); admin.namespaces().createNamespace(testTenant + "/" + testNamespace, Set.of(testCluster)); admin.topics().createPartitionedTopic(testTopic, 2); - Producer producer = pulsarClient.newProducer().topic(testTenant + "/" + testNamespace + "/" + Producer producer = pulsarClient.newProducer().topic(testTenant + "/" + testNamespace + "/" + "dummy-topic").create(); producer.close(); waitForZooKeeperWatchers(); diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/TopicPoliciesTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/TopicPoliciesTest.java index 47b0d63aba635..65f61a3181e6c 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/TopicPoliciesTest.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/TopicPoliciesTest.java @@ -156,7 +156,7 @@ protected void setup() throws Exception { admin.namespaces().createNamespace(testTenant + "/" + testNamespace, Set.of("test")); admin.namespaces().createNamespace(myNamespaceV1); admin.topics().createPartitionedTopic(testTopic, testTopicPartitions); - Producer producer = pulsarClient.newProducer().topic(testTopic).create(); + Producer producer = pulsarClient.newProducer().topic(testTopic).create(); producer.close(); waitForZooKeeperWatchers(); } @@ -496,7 +496,7 @@ public void testPriorityOfGlobalPolicies(String clientRequestType) throws Except final String httpPath = "/admin/v2/persistent/" + namespace + "/" + TopicName.get(topic).getLocalName() + "/maxConsumers"; admin.topics().createNonPartitionedTopic(topic); - Producer producer = pulsarClient.newProducer().topic(topic).create(); + Producer producer = pulsarClient.newProducer().topic(topic).create(); PersistentTopic persistentTopic = (PersistentTopic) pulsar.getBrokerService().getTopics().get(topic).get().get(); @@ -577,7 +577,7 @@ public void testPriorityOfGlobalPolicies2(String clientRequestType) throws Excep final String httpPath = "/admin/v2/persistent/" + namespace + "/" + TopicName.get(topic).getLocalName() + "/maxConsumers"; admin.topics().createNonPartitionedTopic(topic); - Producer producer = pulsarClient.newProducer().topic(topic).create(); + Producer producer = pulsarClient.newProducer().topic(topic).create(); PersistentTopic persistentTopic = (PersistentTopic) pulsar.getBrokerService().getTopics().get(topic).get().get(); @@ -2392,19 +2392,19 @@ public void testGetSetSubscribeRate() throws Exception { PulsarClient pulsarClient2 = newPulsarClient(lookupUrl.toString(), 0); PulsarClient pulsarClient3 = newPulsarClient(lookupUrl.toString(), 0); - Consumer consumer1 = pulsarClient1.newConsumer().subscriptionName("sub1") + Consumer consumer1 = pulsarClient1.newConsumer().subscriptionName("sub1") .topic(persistenceTopic).consumerName("test").subscribe(); Assert.assertNotNull(consumer1); consumer1.close(); pulsarClient1.shutdown(); - Consumer consumer2 = pulsarClient2.newConsumer().subscriptionName("sub1") + Consumer consumer2 = pulsarClient2.newConsumer().subscriptionName("sub1") .topic(persistenceTopic).consumerName("test").subscribe(); Assert.assertNotNull(consumer2); consumer2.close(); pulsarClient2.shutdown(); - Consumer consumer3 = null; + Consumer consumer3 = null; try { consumer3 = pulsarClient3.newConsumer().subscriptionName("sub1") @@ -2797,8 +2797,8 @@ private void doTestMaxSubscriptionsFailFast(SubscriptionMode subMode) throws Exc // init cache pulsarClient.newProducer().topic(topic).create().close(); int maxSubInNamespace = 2; - List consumers = new ArrayList<>(); - ConsumerBuilder consumerBuilder = pulsarClient.newConsumer().subscriptionMode(subMode) + List> consumers = new ArrayList<>(); + ConsumerBuilder consumerBuilder = pulsarClient.newConsumer().subscriptionMode(subMode) .subscriptionType(SubscriptionType.Shared).topic(topic); admin.namespaces().setMaxSubscriptionsPerTopic(myNamespace, maxSubInNamespace); Awaitility.await().untilAsserted(() @@ -2816,7 +2816,7 @@ private void doTestMaxSubscriptionsFailFast(SubscriptionMode subMode) throws Exc //fail fast assertTrue(System.currentTimeMillis() - start < 3000); //clean - for (Consumer consumer : consumers) { + for (Consumer consumer : consumers) { consumer.close(); } } @@ -2896,7 +2896,7 @@ public void testMaxUnackedMessagesOnSubscriptionPriority() throws Exception { final String topic = "persistent://" + myNamespace + "/test-" + UUID.randomUUID(); // init cache @Cleanup - Producer producer = pulsarClient.newProducer().topic(topic).create(); + Producer producer = pulsarClient.newProducer().topic(topic).create(); //default value is null assertNull(admin.namespaces().getMaxUnackedMessagesPerSubscription(myNamespace)); int msgNum = 100; @@ -2957,7 +2957,7 @@ public void testMaxUnackedMessagesOnSubscriptionPriority() throws Exception { assertEquals(messages.size(), defaultMaxUnackedMsgOnBroker); } - private void produceMsg(Producer producer, int msgNum) throws Exception{ + private void produceMsg(Producer producer, int msgNum) throws Exception{ for (int i = 0; i < msgNum; i++) { producer.send("msg".getBytes()); } @@ -3280,12 +3280,12 @@ public void testNonPersistentMaxConsumerOnSub() throws Exception { conf.setMaxConsumersPerSubscription(maxConsumerPerSubInBroker); final String topic = "non-persistent://" + myNamespace + "/test-" + UUID.randomUUID(); admin.topics().createPartitionedTopic(topic, 3); - Producer producer = pulsarClient.newProducer().topic(topic).create(); + Producer producer = pulsarClient.newProducer().topic(topic).create(); final String subName = "my-sub"; - ConsumerBuilder builder = pulsarClient.newConsumer() + ConsumerBuilder builder = pulsarClient.newConsumer() .subscriptionType(SubscriptionType.Shared) .subscriptionName(subName).topic(topic); - Consumer consumer = builder.subscribe(); + Consumer consumer = builder.subscribe(); try { builder.subscribe(); @@ -3300,7 +3300,7 @@ public void testNonPersistentMaxConsumerOnSub() throws Exception { assertEquals(admin.namespaces().getMaxConsumersPerSubscription(myNamespace).intValue(), maxConsumerPerSubInNs); }); - Consumer consumer2 = builder.subscribe(); + Consumer consumer2 = builder.subscribe(); try { builder.subscribe(); fail("should fail"); @@ -3315,7 +3315,7 @@ public void testNonPersistentMaxConsumerOnSub() throws Exception { assertEquals(admin.topicPolicies().getMaxConsumersPerSubscription(topic).intValue(), maxConsumerPerSubInTopic); }); - Consumer consumer3 = builder.subscribe(); + Consumer consumer3 = builder.subscribe(); try { builder.subscribe(); fail("should fail"); @@ -3512,13 +3512,13 @@ public void testPoliciesCanBeDeletedWithTopic() throws Exception { CompletableFuture future = (CompletableFuture) field.get(persistentTopic); Awaitility.await().untilAsserted(() -> assertTrue(future.isDone())); - Consumer consumer = pulsarClient.newConsumer() + Consumer consumer = pulsarClient.newConsumer() .subscriptionInitialPosition(SubscriptionInitialPosition.Earliest) .readCompacted(true) .topic(topicPoliciesTopic).subscriptionName("sub").subscribe(); int count = 0; while (true) { - Message message = consumer.receive(1, TimeUnit.SECONDS); + Message message = consumer.receive(1, TimeUnit.SECONDS); if (message != null) { count++; consumer.acknowledge(message); @@ -3547,7 +3547,7 @@ public void testPoliciesCanBeDeletedWithTopic() throws Exception { .topic(topicPoliciesTopic).subscriptionName("sub").subscribe(); count = 0; while (true) { - Message message = consumer.receive(1, TimeUnit.SECONDS); + Message message = consumer.receive(1, TimeUnit.SECONDS); if (message != null) { count++; consumer.acknowledge(message); diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/v3/AdminApiTransactionTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/v3/AdminApiTransactionTest.java index 2f2e98a08701c..221ef4df4830a 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/v3/AdminApiTransactionTest.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/v3/AdminApiTransactionTest.java @@ -1039,7 +1039,7 @@ public void testPeekMessageForShowAllMessages() throws Exception { for (int i = 0; i < 4 * n; i++) { Message peekMsg = peekMsgs.get(i); - MessageImpl peekMsgImpl = (MessageImpl) peekMsg; + MessageImpl peekMsgImpl = (MessageImpl) peekMsg; MessageMetadata metadata = peekMsgImpl.getMessageBuilder(); if (metadata.hasMarkerType()) { assertTrue(metadata.getMarkerType() == MarkerType.TXN_COMMIT_VALUE diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/auth/MockedPulsarServiceBaseTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/auth/MockedPulsarServiceBaseTest.java index 73bb407f52ad1..f21d7d6980e95 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/auth/MockedPulsarServiceBaseTest.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/auth/MockedPulsarServiceBaseTest.java @@ -759,7 +759,7 @@ public Object[][] incorrectPersistentPolicies() { }; } - protected ServiceProducer getServiceProducer(ProducerImpl clientProducer, String topicName) { + protected ServiceProducer getServiceProducer(ProducerImpl clientProducer, String topicName) { PersistentTopic persistentTopic = (PersistentTopic) pulsar.getBrokerService().getTopic(topicName, false).join().get(); org.apache.pulsar.broker.service.Producer serviceProducer = @@ -788,7 +788,7 @@ protected void sleepSeconds(int seconds){ private static void reconnectAllConnections(PulsarClientImpl c) throws Exception { ConnectionPool pool = c.getCnxPool(); - Method closeAllConnections = ConnectionPool.class.getDeclaredMethod("closeAllConnections", new Class[]{}); + Method closeAllConnections = ConnectionPool.class.getDeclaredMethod("closeAllConnections", new Class[]{}); closeAllConnections.setAccessible(true); closeAllConnections.invoke(pool, new Object[]{}); } diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/cache/BrokerEntryCacheRollingRestartTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/cache/BrokerEntryCacheRollingRestartTest.java index bc45a7e792702..4fc35468be7dd 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/cache/BrokerEntryCacheRollingRestartTest.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/cache/BrokerEntryCacheRollingRestartTest.java @@ -154,6 +154,7 @@ public void testTailingReadsRollingRestart() throws Exception { .create(); // Create consumers in paused state with receiver queue size of 50 + @SuppressWarnings({"unchecked", "rawtypes"}) Consumer[] consumers = new Consumer[numConsumers]; List consumerPulsarClients = new ArrayList<>(); @Cleanup diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/cache/BrokerEntryCacheTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/cache/BrokerEntryCacheTest.java index f857c5c2ef658..8f4a49733c970 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/cache/BrokerEntryCacheTest.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/cache/BrokerEntryCacheTest.java @@ -160,6 +160,7 @@ public void testTailingReadsKeySharedSlowConsumer() throws Exception { .create(); // Create consumers on the tail (reading from latest) + @SuppressWarnings({"unchecked", "rawtypes"}) Consumer[] consumers = new Consumer[numConsumers]; for (int i = 0; i < numConsumers; i++) { consumers[i] = pulsarClient.newConsumer(Schema.INT64) @@ -331,6 +332,7 @@ public void testCatchUpReadsWithFailureProxyDisconnectingAllConnections() throws .create(); // Create consumers in paused state with receiver queue size of 50 + @SuppressWarnings({"unchecked", "rawtypes"}) Consumer[] consumers = new Consumer[numConsumers]; for (int i = 0; i < numConsumers; i++) { consumers[i] = pulsarClient.newConsumer(Schema.INT64) @@ -491,6 +493,7 @@ public void testTailingReadsClearsCacheAfterCacheTimeout() throws Exception { .create(); // Create consumers on the tail (reading from latest) + @SuppressWarnings({"unchecked", "rawtypes"}) Consumer[] consumers = new Consumer[numConsumers]; for (int i = 0; i < numConsumers; i++) { consumers[i] = pulsarClient.newConsumer(Schema.INT64) @@ -602,6 +605,7 @@ public void testExpectedReads() throws Exception { .create(); // Create consumers on the tail (reading from latest) + @SuppressWarnings({"unchecked", "rawtypes"}) Consumer[] consumers = new Consumer[numConsumers]; for (int i = 0; i < numConsumers; i++) { consumers[i] = pulsarClient.newConsumer(Schema.INT64) diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/cache/MinimumBacklogCacheStrategyTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/cache/MinimumBacklogCacheStrategyTest.java index 9505d20831e58..98afae8bf8480 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/cache/MinimumBacklogCacheStrategyTest.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/cache/MinimumBacklogCacheStrategyTest.java @@ -86,6 +86,7 @@ public void testBacklogConsumerCacheReads() throws Exception { final String topicName = "cache-read"; final String sub1 = "sub"; int totalSub = 10; + @SuppressWarnings({"unchecked", "rawtypes"}) Consumer[] consumers = new Consumer[totalSub]; for (int i = 0; i < totalSub; i++) { diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/intercept/ExceptionsBrokerInterceptorTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/intercept/ExceptionsBrokerInterceptorTest.java index 82078da7612f2..2229a89a68fab 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/intercept/ExceptionsBrokerInterceptorTest.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/intercept/ExceptionsBrokerInterceptorTest.java @@ -84,7 +84,7 @@ public void testMessageAckedExceptions() throws Exception { Producer producer = pulsarClient.newProducer().topic(topic).create(); - ConsumerImpl consumer = (ConsumerImpl) pulsarClient + ConsumerImpl consumer = (ConsumerImpl) pulsarClient .newConsumer() .topic(topic) .subscriptionName(subName) @@ -100,7 +100,7 @@ public void testMessageAckedExceptions() throws Exception { } int receiveCounter = 0; - Message message; + Message message; while ((message = consumer.receive(3, TimeUnit.SECONDS)) != null) { receiveCounter++; consumer.acknowledge(message); diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/loadbalance/ModularLoadManagerStrategyTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/loadbalance/ModularLoadManagerStrategyTest.java index fae01b0adc0ff..7e46309072591 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/loadbalance/ModularLoadManagerStrategyTest.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/loadbalance/ModularLoadManagerStrategyTest.java @@ -233,7 +233,7 @@ public void testLeastResourceUsageWithWeightWithArithmeticException() } public void testRoundRobinBrokerSelector() throws IllegalAccessException { - Set brokers = new LinkedHashSet(Arrays.asList("1", "2", "3")); + Set brokers = new LinkedHashSet<>(Arrays.asList("1", "2", "3")); int n = brokers.size(); RoundRobinBrokerSelector strategy = new RoundRobinBrokerSelector(); @@ -245,13 +245,13 @@ public void testRoundRobinBrokerSelector() throws IllegalAccessException { assertEquals(strategy.selectBroker(brokers, null, null, null), Optional.of(id)); } - Set brokers2 = new LinkedHashSet(Arrays.asList("2", "3", "1")); + Set brokers2 = new LinkedHashSet<>(Arrays.asList("2", "3", "1")); for (; i < 20; i++) { String id = (i % n) + 1 + ""; assertEquals(strategy.selectBroker(brokers2, null, null, null), Optional.of(id)); } - Set brokers3 = new LinkedHashSet(Arrays.asList("1", "2", "4")); + Set brokers3 = new LinkedHashSet<>(Arrays.asList("1", "2", "4")); assertEquals(strategy.selectBroker(brokers3, null, null, null), Optional.of("4")); assertEquals(strategy.selectBroker(brokers3, null, null, null), Optional.of("1")); assertEquals(strategy.selectBroker(brokers3, null, null, null), Optional.of("2")); @@ -259,7 +259,7 @@ public void testRoundRobinBrokerSelector() throws IllegalAccessException { assertEquals(strategy.selectBroker(brokers3, null, null, null), Optional.of("1")); assertEquals(strategy.selectBroker(brokers3, null, null, null), Optional.of("2")); - Set brokers4 = new LinkedHashSet(Arrays.asList("2", "4")); + Set brokers4 = new LinkedHashSet<>(Arrays.asList("2", "4")); assertEquals(strategy.selectBroker(brokers4, null, null, null), Optional.of("2")); assertEquals(strategy.selectBroker(brokers4, null, null, null), Optional.of("4")); assertEquals(strategy.selectBroker(brokers4, null, null, null), Optional.of("2")); diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/loadbalance/extensions/ExtensibleLoadManagerImplTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/loadbalance/extensions/ExtensibleLoadManagerImplTest.java index 82fed30cb356e..ee4fe5c098868 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/loadbalance/extensions/ExtensibleLoadManagerImplTest.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/loadbalance/extensions/ExtensibleLoadManagerImplTest.java @@ -359,7 +359,9 @@ public void testUnloadUponTopicLookupFailure() throws Exception { NamespaceBundle bundle = pulsar1.getNamespaceService().getBundle(topicName); primaryLoadManager.assign(Optional.empty(), bundle, LookupOptions.builder().build()).get(); + @SuppressWarnings("rawtypes") CompletableFuture future1 = new CompletableFuture(); + @SuppressWarnings("rawtypes") CompletableFuture future2 = new CompletableFuture(); try { pulsar1.getBrokerService().getTopics().put(topicName.toString(), future1); diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/loadbalance/extensions/channel/ServiceUnitStateChannelTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/loadbalance/extensions/channel/ServiceUnitStateChannelTest.java index 108c4a3910659..72d7da564da54 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/loadbalance/extensions/channel/ServiceUnitStateChannelTest.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/loadbalance/extensions/channel/ServiceUnitStateChannelTest.java @@ -289,7 +289,7 @@ public void channelValidationTest() assertEquals(6, errorCnt); @Cleanup("shutdownNow") ExecutorService executor = Executors.newSingleThreadExecutor(); - Future startFuture = executor.submit(() -> { + Future startFuture = executor.submit(() -> { try { channel.start(); } catch (PulsarServerException e) { @@ -304,7 +304,7 @@ public void channelValidationTest() ServiceUnitStateChannelImpl.ChannelState.LeaderElectionServiceStarted, true); assertNotNull(channel.getChannelOwnerAsync().get(2, TimeUnit.SECONDS).get()); - Future closeFuture = executor.submit(() -> { + Future closeFuture = executor.submit(() -> { try { channel.close(); } catch (PulsarServerException e) { @@ -812,7 +812,7 @@ private static Number getMetric(List metrics, String metricName) { public void handleBrokerCreationEventTest() throws IllegalAccessException { var cleanupJobs = getCleanupJobs(channel1); String broker = brokerId2; - var future = new CompletableFuture(); + var future = new CompletableFuture(); cleanupJobs.put(broker, future); ((ServiceUnitStateChannelImpl) channel1).handleBrokerRegistrationEvent(broker, NotificationType.Created); Awaitility.await().atMost(5, TimeUnit.SECONDS).untilAsserted(() -> { @@ -1842,7 +1842,7 @@ public void testActiveGetOwner() throws Exception { // case 5: the owner lookup gets delayed FieldUtils.writeDeclaredField(channel1, "inFlightStateWaitingTimeInMillis", 1000, true); - var delayedFuture = new CompletableFuture(); + var delayedFuture = new CompletableFuture(); doReturn(delayedFuture).when(registry).lookupAsync(eq(broker)); CompletableFuture.runAsync(() -> { try { diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/loadbalance/extensions/models/TopKBundlesTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/loadbalance/extensions/models/TopKBundlesTest.java index 2be3108c63832..16bdacb93cce1 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/loadbalance/extensions/models/TopKBundlesTest.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/loadbalance/extensions/models/TopKBundlesTest.java @@ -288,8 +288,8 @@ public void testLoadBalancerSheddingBundlesWithPoliciesEnabledConfig() throws Me public void testPartitionSort() { Random rand = new Random(); - List> actual = new ArrayList<>(); - List> expected = new ArrayList<>(); + @SuppressWarnings("rawtypes") List> actual = new ArrayList<>(); + @SuppressWarnings("rawtypes") List> expected = new ArrayList<>(); for (int j = 0; j < 100; j++) { Map map = new HashMap<>(); @@ -337,7 +337,7 @@ public void testPartitionSortCompareToContractViolationIssue() { s.cacheSize = 75000000 - (rnd.nextInt(4 * 75000)); stats.add(s); } - List> bundleEntries = new ArrayList<>(); + @SuppressWarnings("rawtypes") List> bundleEntries = new ArrayList<>(); for (NamespaceBundleStats s : stats) { bundleEntries.add(Map.entry("bundle-" + s.msgThroughputIn, s)); diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/loadbalance/extensions/reporter/BrokerLoadDataReporterTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/loadbalance/extensions/reporter/BrokerLoadDataReporterTest.java index 1a729e884bdca..4a4cc877bc599 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/loadbalance/extensions/reporter/BrokerLoadDataReporterTest.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/loadbalance/extensions/reporter/BrokerLoadDataReporterTest.java @@ -55,6 +55,7 @@ @Test(groups = "broker") public class BrokerLoadDataReporterTest { PulsarService pulsar; + @SuppressWarnings("rawtypes") LoadDataStore store; BrokerService brokerService; PulsarStats pulsarStats; diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/loadbalance/extensions/reporter/TopBundleLoadDataReporterTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/loadbalance/extensions/reporter/TopBundleLoadDataReporterTest.java index 84fba58add66f..e1512d92e98e0 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/loadbalance/extensions/reporter/TopBundleLoadDataReporterTest.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/loadbalance/extensions/reporter/TopBundleLoadDataReporterTest.java @@ -55,6 +55,7 @@ @Test(groups = "broker") public class TopBundleLoadDataReporterTest { PulsarService pulsar; + @SuppressWarnings("rawtypes") LoadDataStore store; BrokerService brokerService; PulsarStats pulsarStats; @@ -132,7 +133,7 @@ public void testGenerateLoadData() throws IllegalAccessException { expected.update(bundleStats, 0); assertEquals(target.generateLoadData(), expected.getLoadData()); - doReturn(new HashMap()).when(brokerService).getBundleStats(); + doReturn(new HashMap<>()).when(brokerService).getBundleStats(); FieldUtils.writeDeclaredField(target, "lastBundleStatsUpdatedAt", 0L, true); expected = new TopKBundles(pulsar); assertEquals(target.generateLoadData(), expected.getLoadData()); diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/loadbalance/extensions/scheduler/SplitSchedulerTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/loadbalance/extensions/scheduler/SplitSchedulerTest.java index 0b9af26709cc4..54d1e9febfbcf 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/loadbalance/extensions/scheduler/SplitSchedulerTest.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/loadbalance/extensions/scheduler/SplitSchedulerTest.java @@ -104,7 +104,7 @@ public void setUp() { @Test(timeOut = 30 * 1000) public void testExecuteSuccess() { - AtomicReference> reference = new AtomicReference(); + AtomicReference> reference = new AtomicReference<>(); SplitCounter counter = new SplitCounter(); SplitManager manager = mock(SplitManager.class); SplitScheduler scheduler = new SplitScheduler(pulsar, channel, manager, counter, reference, context, strategy); @@ -134,7 +134,7 @@ public void testExecuteSuccess() { @Test(timeOut = 30 * 1000) public void testExecuteFailure() { - AtomicReference> reference = new AtomicReference(); + AtomicReference> reference = new AtomicReference<>(); SplitCounter counter = new SplitCounter(); SplitManager manager = new SplitManager(counter); SplitScheduler scheduler = new SplitScheduler(pulsar, channel, manager, counter, reference, context, strategy); diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/loadbalance/extensions/strategy/DefaultNamespaceBundleSplitStrategyTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/loadbalance/extensions/strategy/DefaultNamespaceBundleSplitStrategyTest.java index d59504da76a08..a3649ff4af18c 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/loadbalance/extensions/strategy/DefaultNamespaceBundleSplitStrategyTest.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/loadbalance/extensions/strategy/DefaultNamespaceBundleSplitStrategyTest.java @@ -120,7 +120,7 @@ void setup() { doReturn(namespaceBundleFactory).when(namespaceService).getNamespaceBundleFactory(); doReturn(brokerRegistry).when(loadManagerContext).brokerRegistry(); doReturn(broker).when(brokerRegistry).getBrokerId(); - doReturn(new AtomicReference(loadManagerWrapper)).when(pulsar).getLoadManager(); + doReturn(new AtomicReference<>(loadManagerWrapper)).when(pulsar).getLoadManager(); doReturn(loadManager).when(loadManagerWrapper).get(); doReturn(channel).when(loadManager).getServiceUnitStateChannel(); doReturn(true).when(channel).isOwner(any()); diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/loadbalance/impl/ModularLoadManagerImplTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/loadbalance/impl/ModularLoadManagerImplTest.java index da12c84e19791..b47e5cdff793f 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/loadbalance/impl/ModularLoadManagerImplTest.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/loadbalance/impl/ModularLoadManagerImplTest.java @@ -1149,7 +1149,7 @@ public void testRepeatSplitBundle() throws Exception { PulsarClient pulsarClient = PulsarClient.builder().serviceUrl(pulsar1.getBrokerServiceUrl()).build(); // create a lot of topic to fully distributed among bundles. - List consumers = new ArrayList<>(); + List> consumers = new ArrayList<>(); for (int i = 0; i < 10; i++) { String topicNameI = topicName + i; admin1.topics().createPartitionedTopic(topicNameI, 20); @@ -1175,7 +1175,7 @@ public void testRepeatSplitBundle() throws Exception { primaryLoadManager.updateAll(); Assert.assertFalse(loadData.getBundleData().containsKey(bundleKey)); - for (Consumer consumer : consumers) { + for (Consumer consumer : consumers) { consumer.close(); } } diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/OneWayReplicatorTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/OneWayReplicatorTest.java index 195b28413736a..fcf392f1d328b 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/OneWayReplicatorTest.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/OneWayReplicatorTest.java @@ -486,7 +486,7 @@ public void testTopicCloseWhenInternalProducerCloseErrorOnce() throws Exception // Mock an error when calling "replicator.disconnect()" AtomicBoolean closeFailed = new AtomicBoolean(true); final ProducerImpl mockProducer = Mockito.mock(ProducerImpl.class); - final AtomicReference originalProducer1 = new AtomicReference(); + final AtomicReference> originalProducer1 = new AtomicReference<>(); doAnswer(invocation -> { if (closeFailed.get()) { return CompletableFuture.failedFuture(new Exception("mocked ex")); @@ -501,8 +501,8 @@ public void testTopicCloseWhenInternalProducerCloseErrorOnce() throws Exception // Verify: After "replicator.producer.closeAsync()" retry again, the "replicator.producer" will be closed // successful. closeFailed.set(false); - AtomicReference topic2 = new AtomicReference(); - AtomicReference replicator2 = new AtomicReference(); + AtomicReference topic2 = new AtomicReference<>(); + AtomicReference replicator2 = new AtomicReference<>(); Awaitility.await().untilAsserted(() -> { topic2.set((PersistentTopic) pulsar1.getBrokerService().getTopic(topicName, false).join().get()); replicator2.set((PersistentReplicator) topic2.get().getReplicators().values().iterator().next()); @@ -548,9 +548,9 @@ private Runnable injectMockReplicatorProducerBuilder( // Inject producer decorator. doAnswer(invocation -> { - Schema schema = (Schema) invocation.getArguments()[0]; + Schema schema = (Schema) invocation.getArguments()[0]; ProducerBuilderImpl producerBuilder = (ProducerBuilderImpl) internalClient.newProducer(schema); - ProducerBuilder spyProducerBuilder = spy(producerBuilder); + ProducerBuilder spyProducerBuilder = spy(producerBuilder); doAnswer(ignore -> { CompletableFuture producerFuture = new CompletableFuture<>(); producerBuilder.createAsync().whenComplete((p, t) -> { diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/PersistentTopicTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/PersistentTopicTest.java index 5d7f88fb3bd5e..675cfb30cfb2f 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/PersistentTopicTest.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/PersistentTopicTest.java @@ -1710,7 +1710,7 @@ public void testAtomicReplicationRemoval() throws Exception { when(pulsarClientMock.getCnxPool()).thenReturn(connectionPool); when(pulsarClientMock.newProducer(any())).thenAnswer( invocation -> { - ProducerBuilderImpl producerBuilder = + @SuppressWarnings("rawtypes") ProducerBuilderImpl producerBuilder = new ProducerBuilderImpl(pulsarClientMock, invocation.getArgument(0)) { @Override public CompletableFuture createAsync() { diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/ReplicatedSubscriptionTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/ReplicatedSubscriptionTest.java index 98ef5ba3c0e06..6c4b5b93cda43 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/ReplicatedSubscriptionTest.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/ReplicatedSubscriptionTest.java @@ -341,13 +341,13 @@ public void testReplicatedSubscribeAndSwitchToStandbyCluster() throws Exception // Since the cluster1 was not crash, all messages will be replicated to the cluster2. consumer1.close(); final PulsarClient client2 = PulsarClient.builder().serviceUrl(url2.toString()).build(); - final Consumer consumer2 = client2.newConsumer(Schema.AUTO_CONSUME()).topic(topicName) + final Consumer consumer2 = client2.newConsumer(Schema.AUTO_CONSUME()).topic(topicName) .subscriptionName(subscriptionName).replicateSubscriptionState(isReplicatedSubscription).subscribe(); // Verify all messages will be consumed. Awaitility.await().untilAsserted(() -> { while (true) { - Message message = consumer2.receive(2, TimeUnit.SECONDS); + Message message = consumer2.receive(2, TimeUnit.SECONDS); if (message != null) { receivedMessages.add(message.getValue().toString()); consumer2.acknowledge(message); diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/TopicGCTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/TopicGCTest.java index a3d6ae39e3e43..15cea03150e30 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/TopicGCTest.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/TopicGCTest.java @@ -88,7 +88,7 @@ public Object[][] subTopicTypes() { }; } - private void setSubscribeTopic(ConsumerBuilder consumerBuilder, SubscribeTopicType subscribeTopicType, + private void setSubscribeTopic(ConsumerBuilder consumerBuilder, SubscribeTopicType subscribeTopicType, String topicName, String topicPattern) { if (subscribeTopicType.equals(SubscribeTopicType.MULTI_PARTITIONED_TOPIC)) { consumerBuilder.topic(topicName); diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/TransactionalReplicateSubscriptionTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/TransactionalReplicateSubscriptionTest.java index 6f71480f1a913..514ab57de2f65 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/TransactionalReplicateSubscriptionTest.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/TransactionalReplicateSubscriptionTest.java @@ -156,13 +156,13 @@ public void testReplicatedSubscribeAndSwitchToStandbyClusterWithTransaction() th // Since the cluster1 was not crash, all messages will be replicated to the cluster2. consumer1.close(); final PulsarClient client2 = PulsarClient.builder().serviceUrl(url2.toString()).build(); - final Consumer consumer2 = client2.newConsumer(Schema.AUTO_CONSUME()).topic(topicName) + final Consumer consumer2 = client2.newConsumer(Schema.AUTO_CONSUME()).topic(topicName) .subscriptionName(subscriptionName).replicateSubscriptionState(isReplicatedSubscription).subscribe(); // Verify all messages will be consumed. Awaitility.await().untilAsserted(() -> { while (true) { - Message message = consumer2.receive(2, TimeUnit.SECONDS); + Message message = consumer2.receive(2, TimeUnit.SECONDS); if (message != null) { receivedMessages.add(message.getValue().toString()); consumer2.acknowledge(message); diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/persistent/PersistentReplicatorInflightTaskTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/persistent/PersistentReplicatorInflightTaskTest.java index e8a7a11a2db13..6b0d393aec3f9 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/persistent/PersistentReplicatorInflightTaskTest.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/persistent/PersistentReplicatorInflightTaskTest.java @@ -91,7 +91,7 @@ public void testReplicationTaskStoppedAfterTopicClosed() throws Exception { injectedTask.setEntries(Collections.emptyList()); InFlightTask spyTask = spy(injectedTask); replicator.inFlightTasks.add(spyTask); - doAnswer(new Answer() { + doAnswer(new Answer() { @Override public Object answer(InvocationOnMock invocationOnMock) throws Throwable { counter.incrementAndGet(); diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/persistent/PersistentTopicProtectedMethodsTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/persistent/PersistentTopicProtectedMethodsTest.java index e51da48042e6c..a2ec1f0bed774 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/persistent/PersistentTopicProtectedMethodsTest.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/persistent/PersistentTopicProtectedMethodsTest.java @@ -96,7 +96,7 @@ public void testEstimatedTimeBasedBacklogQuotaCheckWhenNoBacklog() throws Except // moving the cursor's mark-delete position past the LAC (e.g., 10:-1 vs 9:1). assertTrue(cursor.getMarkDeletedPosition().compareTo(ml.getLastConfirmedEntry()) >= 0); }); - CompletableFuture completableFuture = new CompletableFuture(); + CompletableFuture completableFuture = new CompletableFuture<>(); ml.trimConsumedLedgersInBackground(completableFuture); completableFuture.join(); Awaitility.await().untilAsserted(() -> { diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/persistent/PersistentTopicTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/persistent/PersistentTopicTest.java index 5b3c705688c7f..1f84993215beb 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/persistent/PersistentTopicTest.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/persistent/PersistentTopicTest.java @@ -331,7 +331,7 @@ public void testPersistentPartitionedTopicUnload() throws Exception { NamespaceBundle bundle = pulsar.getNamespaceService().getBundle(TopicName.get(topicName)); pulsar.getNamespaceService().unloadNamespaceBundle(bundle, 5, TimeUnit.SECONDS).get(); - for (Producer producer : producerSet) { + for (Producer producer : producerSet) { producer.close(); } } @@ -360,7 +360,7 @@ public void testConcurrentClose(boolean closeWithoutWaitingClientDisconnectInFir * The other 19 calls: get the cached value which related {@link PersistentTopic#closeFutures}. */ assertTrue(futureMap.size() <= 3); - for (List list : futureMap.values()){ + for (List list : futureMap.values()){ if (list.size() == 1){ // This is the first call, the future is the return value of `topic.close`. } else { @@ -589,7 +589,7 @@ public void testDeleteTopicFail() throws Exception { doReturn(brokerService).when(pulsar).getBrokerService(); // Create a sub, and send one message. - Consumer consumer1 = pulsarClient.newConsumer(Schema.STRING).topic(fullyTopicName).subscriptionName("sub1") + Consumer consumer1 = pulsarClient.newConsumer(Schema.STRING).topic(fullyTopicName).subscriptionName("sub1") .subscribe(); consumer1.close(); Producer producer = pulsarClient.newProducer(Schema.STRING).topic(fullyTopicName).create(); @@ -618,7 +618,7 @@ public void testDeleteTopicFail() throws Exception { } // Assert topic works after deleting failure. - Consumer consumer2 = pulsarClient.newConsumer(Schema.STRING).topic(fullyTopicName).subscriptionName("sub1") + Consumer consumer2 = pulsarClient.newConsumer(Schema.STRING).topic(fullyTopicName).subscriptionName("sub1") .subscribe(); org.testng.Assert.assertEquals("1", consumer2.receive(2, TimeUnit.SECONDS).getValue()); consumer2.close(); diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/systopic/PartitionedSystemTopicTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/systopic/PartitionedSystemTopicTest.java index 89cbbb2655336..59352db0052ef 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/systopic/PartitionedSystemTopicTest.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/systopic/PartitionedSystemTopicTest.java @@ -99,7 +99,7 @@ public void testAutoCreatedPartitionedSystemTopic() throws Exception { NamespaceEventsSystemTopicFactory systemTopicFactory = new NamespaceEventsSystemTopicFactory(pulsarClient); TopicPoliciesSystemTopicClient systemTopicClientForNamespace = systemTopicFactory .createTopicPoliciesSystemTopicClient(NamespaceName.get(ns)); - SystemTopicClient.Reader reader = systemTopicClientForNamespace.newReader(); + SystemTopicClient.Reader reader = systemTopicClientForNamespace.newReader(); int partitions = admin.topics().getPartitionedTopicMetadata( String.format("persistent://%s/%s", ns, SystemTopicNames.NAMESPACE_EVENTS_LOCAL_NAME)).partitions; @@ -326,8 +326,8 @@ public void testSystemTopicNotCheckExceed() throws Exception { NamespaceEventsSystemTopicFactory systemTopicFactory = new NamespaceEventsSystemTopicFactory(pulsarClient); TopicPoliciesSystemTopicClient systemTopicClientForNamespace = systemTopicFactory .createTopicPoliciesSystemTopicClient(NamespaceName.get(ns)); - SystemTopicClient.Reader reader1 = systemTopicClientForNamespace.newReader(); - SystemTopicClient.Reader reader2 = systemTopicClientForNamespace.newReader(); + SystemTopicClient.Reader reader1 = systemTopicClientForNamespace.newReader(); + SystemTopicClient.Reader reader2 = systemTopicClientForNamespace.newReader(); conf.setMaxSameAddressProducersPerTopic(1); admin.namespaces().setMaxProducersPerTopic(ns, 1); diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/tools/BrokerToolTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/tools/BrokerToolTest.java index e461d3c904b9f..b40a3e629af42 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/tools/BrokerToolTest.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/tools/BrokerToolTest.java @@ -47,7 +47,7 @@ public void testGenerateDocs() throws Exception { String message = baoStream.toString(); - Class argumentsClass = Class.forName("org.apache.pulsar.broker.tools.LoadReportCommand"); + Class argumentsClass = Class.forName("org.apache.pulsar.broker.tools.LoadReportCommand"); Field[] fields = argumentsClass.getDeclaredFields(); for (Field field : fields) { boolean fieldHasAnno = field.isAnnotationPresent(Option.class); diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/transaction/SegmentAbortedTxnProcessorTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/transaction/SegmentAbortedTxnProcessorTest.java index 30e308b30ebae..33be818a0b065 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/transaction/SegmentAbortedTxnProcessorTest.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/transaction/SegmentAbortedTxnProcessorTest.java @@ -157,7 +157,7 @@ private void waitTaskExecuteCompletely(AbortedTxnProcessor processor) throws Exc Field taskQueueField = SnapshotSegmentAbortedTxnProcessorImpl.PersistentWorker.class .getDeclaredField("taskQueue"); taskQueueField.setAccessible(true); - Queue queue = (Queue) taskQueueField.get(persistentWorker); + Queue queue = (Queue) taskQueueField.get(persistentWorker); Awaitility.await().untilAsserted(() -> assertEquals(queue.size(), 0)); } @@ -193,8 +193,9 @@ public void testFuturesCanCompleteWhenItIsCanceled() throws Exception { Field taskQueueField = SnapshotSegmentAbortedTxnProcessorImpl.PersistentWorker.class .getDeclaredField("taskQueue"); taskQueueField.setAccessible(true); - Supplier task = CompletableFuture::new; - Queue queue = (Queue) taskQueueField.get(persistentWorker); + Supplier task = CompletableFuture::new; + @SuppressWarnings({"unchecked", "rawtypes"}) + Queue queue = (Queue) taskQueueField.get(persistentWorker); queue.add(new MutablePair<>(SnapshotSegmentAbortedTxnProcessorImpl.PersistentWorker.OperationType.WriteSegment, new MutablePair<>(new CompletableFuture<>(), task))); try { diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/transaction/TopicTransactionBufferRecoverTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/transaction/TopicTransactionBufferRecoverTest.java index 7f64d51fcbe85..7d9978c160042 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/transaction/TopicTransactionBufferRecoverTest.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/transaction/TopicTransactionBufferRecoverTest.java @@ -254,7 +254,7 @@ private void recoverTest(String testTopic) throws Exception { } private void makeTBSnapshotReaderTimeoutIfFirstRead(TopicName topicName) throws Exception { - SystemTopicClient.Reader mockReader = mock(SystemTopicClient.Reader.class); + SystemTopicClient.Reader mockReader = mock(SystemTopicClient.Reader.class); AtomicBoolean isFirstCallOfMethodHasMoreEvents = new AtomicBoolean(); AtomicBoolean isFirstCallOfMethodHasReadNext = new AtomicBoolean(); AtomicBoolean isFirstCallOfMethodHasReadNextAsync = new AtomicBoolean(); @@ -276,7 +276,7 @@ private void makeTBSnapshotReaderTimeoutIfFirstRead(TopicName topicName) throws }).when(mockReader).readNext(); doAnswer(invocation -> { - CompletableFuture future = new CompletableFuture<>(); + CompletableFuture> future = new CompletableFuture<>(); new Thread(() -> { if (isFirstCallOfMethodHasReadNextAsync.compareAndSet(false, true)){ // Just stuck the thread. @@ -296,9 +296,9 @@ private void makeTBSnapshotReaderTimeoutIfFirstRead(TopicName topicName) throws for (PulsarService pulsarService : pulsarServiceList){ // Init prop: lastMessageIdInBroker. - final SystemTopicTxnBufferSnapshotService tbSnapshotService = + final SystemTopicTxnBufferSnapshotService tbSnapshotService = pulsarService.getTransactionBufferSnapshotServiceFactory().getTxnBufferSnapshotService(); - SystemTopicTxnBufferSnapshotService spyTbSnapshotService = spy(tbSnapshotService); + SystemTopicTxnBufferSnapshotService spyTbSnapshotService = spy(tbSnapshotService); doAnswer(invocation -> CompletableFuture.completedFuture(mockReader)) .when(spyTbSnapshotService).createReader(topicName); Field field = diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/transaction/TransactionConsumeTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/transaction/TransactionConsumeTest.java index 16ce35214dc95..41adb7bf59a0d 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/transaction/TransactionConsumeTest.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/transaction/TransactionConsumeTest.java @@ -295,7 +295,7 @@ public void testMessageRedelivery() throws Exception { dispatcher.readMoreEntries(); // shared consumer should not receive the redelivered aborted transaction messages - Message message = sharedConsumer.receive(5, TimeUnit.SECONDS); + Message message = sharedConsumer.receive(5, TimeUnit.SECONDS); Assert.assertNull(message); log.info("TransactionConsumeTest testMessageRedelivery finish."); diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/transaction/TransactionTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/transaction/TransactionTest.java index 9a8ce266b1fc9..1cc4f90732749 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/transaction/TransactionTest.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/transaction/TransactionTest.java @@ -1425,7 +1425,7 @@ public void testTransactionAckMessages() throws Exception { .subscriptionName(subName) .subscribe(); List messageIds = new ArrayList<>(); - for (Message message : messageList) { + for (Message message : messageList) { messageIds.add(message.getMessageId()); } for (int i = 0; i < 4; i++) { @@ -1559,7 +1559,7 @@ public void testPendingAckReplayChangeStateError() throws InterruptedException, when(executorProvider.getExecutor(any(Object.class))).thenReturn(executorService); // Mock pendingAckStore. PendingAckStore pendingAckStore = mock(PendingAckStore.class); - doAnswer(new Answer() { + doAnswer(new Answer() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { executorService.execute(()->{ @@ -1825,26 +1825,35 @@ public void testTBSnapshotWriter() throws Exception { // inject a failed writer future CompletableFuture> writerFuture = new CompletableFuture<>(); for (PulsarService pulsarService : pulsarServiceList) { + @SuppressWarnings("rawtypes") SystemTopicTxnBufferSnapshotService bufferSnapshotService = pulsarService.getTransactionBufferSnapshotServiceFactory().getTxnBufferSnapshotService(); + @SuppressWarnings({"unchecked", "rawtypes"}) ConcurrentHashMap writerMap1 = - ((ConcurrentHashMap) field.get(bufferSnapshotService)); + ((ConcurrentHashMap) field.get(bufferSnapshotService)); + @SuppressWarnings("rawtypes") ReferenceCountedWriter failedCountedWriter = new ReferenceCountedWriter(NamespaceName.get(namespace), writerFuture, bufferSnapshotService); writerMap1.put(NamespaceName.get(namespace), failedCountedWriter); + @SuppressWarnings("rawtypes") SystemTopicTxnBufferSnapshotService segmentSnapshotService = pulsarService.getTransactionBufferSnapshotServiceFactory().getTxnBufferSnapshotSegmentService(); + @SuppressWarnings({"unchecked", "rawtypes"}) ConcurrentHashMap writerMap2 = - ((ConcurrentHashMap) field.get(segmentSnapshotService)); + ((ConcurrentHashMap) field.get(segmentSnapshotService)); + @SuppressWarnings("rawtypes") ReferenceCountedWriter failedCountedWriter2 = new ReferenceCountedWriter(NamespaceName.get(namespace), writerFuture, segmentSnapshotService); writerMap2.put(NamespaceName.get(namespace), failedCountedWriter2); + @SuppressWarnings("rawtypes") SystemTopicTxnBufferSnapshotService indexSnapshotService = pulsarService.getTransactionBufferSnapshotServiceFactory().getTxnBufferSnapshotIndexService(); + @SuppressWarnings({"unchecked", "rawtypes"}) ConcurrentHashMap writerMap3 = - ((ConcurrentHashMap) field.get(indexSnapshotService)); + ((ConcurrentHashMap) field.get(indexSnapshotService)); + @SuppressWarnings("rawtypes") ReferenceCountedWriter failedCountedWriter3 = new ReferenceCountedWriter(NamespaceName.get(namespace), writerFuture, indexSnapshotService); writerMap3.put(NamespaceName.get(namespace), failedCountedWriter3); diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/transaction/pendingack/impl/MLPendingAckStoreTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/transaction/pendingack/impl/MLPendingAckStoreTest.java index 154cbe39d408c..c1bcc893b0fb2 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/transaction/pendingack/impl/MLPendingAckStoreTest.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/transaction/pendingack/impl/MLPendingAckStoreTest.java @@ -230,7 +230,7 @@ public void testMainProcess(boolean writeWithBatch, boolean readWithBatch) throw when(pendingAckHandle.changeToReadyState()).thenReturn(true); // Process controller, mark the replay task already finish. final AtomicInteger processController = new AtomicInteger(); - doAnswer(new Answer() { + doAnswer(new Answer() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { processController.incrementAndGet(); diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/web/plugin/servlet/AdditionalServletWithPulsarServiceTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/web/plugin/servlet/AdditionalServletWithPulsarServiceTest.java index bc8f62cb68df2..8e561c299f80f 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/web/plugin/servlet/AdditionalServletWithPulsarServiceTest.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/web/plugin/servlet/AdditionalServletWithPulsarServiceTest.java @@ -49,6 +49,7 @@ public void testLoadAdditionalServlet() throws Exception { NarClassLoader mockLoader = mock(NarClassLoader.class); when(mockLoader.getServiceDefinition(eq(AdditionalServletUtils.ADDITIONAL_SERVLET_FILE))) .thenReturn(ObjectMapperFactory.getYamlMapper().writer().writeValueAsString(def)); + @SuppressWarnings("rawtypes") Class additionalServletClass = MockAdditionalServletWithClassLoader.class; when(mockLoader.loadClass(eq(MockAdditionalServletWithClassLoader.class.getName()))) .thenReturn(additionalServletClass); diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/client/api/ProducerConsumerBase.java b/pulsar-broker/src/test/java/org/apache/pulsar/client/api/ProducerConsumerBase.java index 90babc00d2adb..685411b05c8c6 100644 --- a/pulsar-broker/src/test/java/org/apache/pulsar/client/api/ProducerConsumerBase.java +++ b/pulsar-broker/src/test/java/org/apache/pulsar/client/api/ProducerConsumerBase.java @@ -77,7 +77,7 @@ protected String newTopicName() { protected ReceivedMessages receiveAndAckMessages( BiFunction ackPredicate, Consumer...consumers) throws Exception { - ReceivedMessages receivedMessages = new ReceivedMessages(); + ReceivedMessages receivedMessages = new ReceivedMessages<>(); receiveMessagesInThreads((consumer, msg) -> { T v = msg.getValue(); MessageId messageId = msg.getMessageId(); diff --git a/pulsar-client-tools-test/src/test/java/org/apache/pulsar/admin/cli/PulsarAdminToolTest.java b/pulsar-client-tools-test/src/test/java/org/apache/pulsar/admin/cli/PulsarAdminToolTest.java index a06f5d44665cf..2cd0876f7f2a7 100644 --- a/pulsar-client-tools-test/src/test/java/org/apache/pulsar/admin/cli/PulsarAdminToolTest.java +++ b/pulsar-client-tools-test/src/test/java/org/apache/pulsar/admin/cli/PulsarAdminToolTest.java @@ -1813,6 +1813,7 @@ public void topics() throws Exception { verify(mockTopics).peekMessages("persistent://myprop/ns1/ds1", "sub1", 3, false, TransactionIsolationLevel.READ_COMMITTED); + @SuppressWarnings("rawtypes") MessageImpl message = mock(MessageImpl.class); when(message.getData()).thenReturn(new byte[]{}); when(message.getMessageId()).thenReturn(new MessageIdImpl(1L, 1L, 1)); @@ -2581,7 +2582,7 @@ void schemas() throws Exception { cmdSchemas.run(split("extract -j " + jarFile + " -c " + className + " -t json persistent://tn1/ns1/tp1")); File file = new File(jarFile); ClassLoader cl = new URLClassLoader(new URL[]{file.toURI().toURL()}); - Class cls = cl.loadClass(className); + Class cls = cl.loadClass(className); SchemaDefinition schemaDefinition = SchemaDefinition.builder() .withPojo(cls) diff --git a/pulsar-client-tools-test/src/test/java/org/apache/pulsar/client/cli/PulsarClientToolForceBatchNum.java b/pulsar-client-tools-test/src/test/java/org/apache/pulsar/client/cli/PulsarClientToolForceBatchNum.java index 896bee0e030af..107c1773c0c5d 100644 --- a/pulsar-client-tools-test/src/test/java/org/apache/pulsar/client/cli/PulsarClientToolForceBatchNum.java +++ b/pulsar-client-tools-test/src/test/java/org/apache/pulsar/client/cli/PulsarClientToolForceBatchNum.java @@ -66,6 +66,7 @@ public void updateConfig(ClientBuilder newBuilder, Authentication authentication replaceProducerCommand(produceCommand); } + @SuppressWarnings("rawtypes") private ClientBuilder mockClientBuilder(ClientBuilder newBuilder) throws Exception { PulsarClientImpl client = (PulsarClientImpl) newBuilder.build(); ProducerBuilder producerBuilder = client.newProducer() diff --git a/pulsar-client/src/test/java/org/apache/pulsar/client/impl/BatchMessageContainerImplTest.java b/pulsar-client/src/test/java/org/apache/pulsar/client/impl/BatchMessageContainerImplTest.java index 3b2ac54b4bdae..28604c6e55b81 100644 --- a/pulsar-client/src/test/java/org/apache/pulsar/client/impl/BatchMessageContainerImplTest.java +++ b/pulsar-client/src/test/java/org/apache/pulsar/client/impl/BatchMessageContainerImplTest.java @@ -145,7 +145,7 @@ public void recoveryAfterOom() { @Test public void testMessagesSize() throws Exception { - ProducerImpl producer = mock(ProducerImpl.class); + ProducerImpl producer = mock(ProducerImpl.class); final ProducerConfigurationData producerConfigurationData = new ProducerConfigurationData(); producerConfigurationData.setCompressionType(CompressionType.NONE); diff --git a/pulsar-client/src/test/java/org/apache/pulsar/client/impl/BuildersTest.java b/pulsar-client/src/test/java/org/apache/pulsar/client/impl/BuildersTest.java index 47183001bad2b..ac450289b9c04 100644 --- a/pulsar-client/src/test/java/org/apache/pulsar/client/impl/BuildersTest.java +++ b/pulsar-client/src/test/java/org/apache/pulsar/client/impl/BuildersTest.java @@ -107,7 +107,7 @@ public void readerBuilderLoadConfTest() throws Exception { ".* must be specified but they cannot be specified at the same time.*") public void shouldNotSetTwoOptAtTheSameTime() throws Exception { PulsarClient client = PulsarClient.builder().serviceUrl("pulsar://localhost:6650").build(); - try (Reader reader = client.newReader().topic("abc").startMessageId(MessageId.latest) + try (Reader reader = client.newReader().topic("abc").startMessageId(MessageId.latest) .startMessageFromRollbackDuration(10, TimeUnit.HOURS).create()) { // no-op } finally { @@ -119,7 +119,7 @@ public void shouldNotSetTwoOptAtTheSameTime() throws Exception { ".* must be specified but they cannot be specified at the same time.*") public void shouldSetOneStartOpt() throws Exception { PulsarClient client = PulsarClient.builder().serviceUrl("pulsar://localhost:6650").build(); - try (Reader reader = client.newReader().topic("abc").create()) { + try (Reader reader = client.newReader().topic("abc").create()) { // no-op } finally { client.close(); diff --git a/pulsar-client/src/test/java/org/apache/pulsar/client/impl/ClientCnxTest.java b/pulsar-client/src/test/java/org/apache/pulsar/client/impl/ClientCnxTest.java index c0a75b09ccea1..9a6be8051070a 100644 --- a/pulsar-client/src/test/java/org/apache/pulsar/client/impl/ClientCnxTest.java +++ b/pulsar-client/src/test/java/org/apache/pulsar/client/impl/ClientCnxTest.java @@ -252,7 +252,7 @@ public void testHandleCloseConsumer() { long consumerId = 1; PulsarClientImpl pulsarClient = mock(PulsarClientImpl.class); when(pulsarClient.getConfiguration()).thenReturn(conf); - ConsumerImpl consumer = mock(ConsumerImpl.class); + ConsumerImpl consumer = mock(ConsumerImpl.class); when(consumer.getClient()).thenReturn(pulsarClient); cnx.registerConsumer(consumerId, consumer); assertEquals(cnx.consumers.size(), 1); @@ -276,7 +276,7 @@ public void testHandleCloseProducer() { long producerId = 1; PulsarClientImpl pulsarClient = mock(PulsarClientImpl.class); when(pulsarClient.getConfiguration()).thenReturn(conf); - ProducerImpl producer = mock(ProducerImpl.class); + ProducerImpl producer = mock(ProducerImpl.class); when(producer.getClient()).thenReturn(pulsarClient); cnx.registerProducer(producerId, producer); assertEquals(cnx.producers.size(), 1); diff --git a/pulsar-client/src/test/java/org/apache/pulsar/client/impl/ConsumerImplTest.java b/pulsar-client/src/test/java/org/apache/pulsar/client/impl/ConsumerImplTest.java index 62d6c0b3f7bb6..3344a7f63bdfd 100644 --- a/pulsar-client/src/test/java/org/apache/pulsar/client/impl/ConsumerImplTest.java +++ b/pulsar-client/src/test/java/org/apache/pulsar/client/impl/ConsumerImplTest.java @@ -70,6 +70,7 @@ public void setUp() { createConsumer(consumerConf); } + @SuppressWarnings("rawtypes") private void createConsumer(ConsumerConfigurationData consumerConf) { executorProvider = new ExecutorProvider(1, "ConsumerImplTest"); internalExecutor = Executors.newSingleThreadScheduledExecutor(); @@ -149,6 +150,7 @@ public void testNotifyPendingReceivedCallback_CompleteWithExceptionWhenMessageIs @Test(invocationTimeOut = 1000) public void testNotifyPendingReceivedCallback_InterceptorsWorksWithPrefetchDisabled() { CompletableFuture> receiveFuture = new CompletableFuture<>(); + @SuppressWarnings("rawtypes") MessageImpl message = mock(MessageImpl.class); ConsumerImpl spy = spy(consumer); @@ -167,6 +169,7 @@ public void testNotifyPendingReceivedCallback_InterceptorsWorksWithPrefetchDisab @Test(invocationTimeOut = 1000) public void testNotifyPendingReceivedCallback_WorkNormally() { CompletableFuture> receiveFuture = new CompletableFuture<>(); + @SuppressWarnings("rawtypes") MessageImpl message = mock(MessageImpl.class); ConsumerImpl spy = spy(consumer); diff --git a/pulsar-client/src/test/java/org/apache/pulsar/client/impl/MessageImplTest.java b/pulsar-client/src/test/java/org/apache/pulsar/client/impl/MessageImplTest.java index f3eb7b434a964..e6d6faa350630 100644 --- a/pulsar-client/src/test/java/org/apache/pulsar/client/impl/MessageImplTest.java +++ b/pulsar-client/src/test/java/org/apache/pulsar/client/impl/MessageImplTest.java @@ -121,7 +121,7 @@ public void testDefaultGetProducerDataAssigned() { bar.setField1(true); // // Check kv.encoding.type default, not set value - byte[] encodeBytes = keyValueSchema.encode(new KeyValue(foo, bar)); + byte[] encodeBytes = keyValueSchema.encode(new KeyValue<>(foo, bar)); MessageMetadata builder = new MessageMetadata() .setProducerName("default"); MessageImpl> msg = MessageImpl.create( @@ -150,7 +150,7 @@ public void testInlineGetProducerDataAssigned() { bar.setField1(true); // Check kv.encoding.type INLINE - byte[] encodeBytes = keyValueSchema.encode(new KeyValue(foo, bar)); + byte[] encodeBytes = keyValueSchema.encode(new KeyValue<>(foo, bar)); MessageMetadata builder = new MessageMetadata() .setProducerName("inline"); MessageImpl> msg = MessageImpl.create( @@ -178,7 +178,7 @@ public void testSeparatedGetProducerDataAssigned() { bar.setField1(true); // Check kv.encoding.type SPRAERATE - byte[] encodeBytes = keyValueSchema.encode(new KeyValue(foo, bar)); + byte[] encodeBytes = keyValueSchema.encode(new KeyValue<>(foo, bar)); MessageMetadata builder = new MessageMetadata() .setProducerName("separated"); builder.setPartitionKey(Base64.getEncoder().encodeToString(fooSchema.encode(foo))); @@ -212,7 +212,7 @@ public void testDefaultAVROVersionGetProducerDataAssigned() { SchemaTestUtils.Bar bar = new SchemaTestUtils.Bar(); bar.setField1(true); - byte[] encodeBytes = keyValueSchema.encode(new KeyValue(foo, bar)); + byte[] encodeBytes = keyValueSchema.encode(new KeyValue<>(foo, bar)); MessageMetadata builder = new MessageMetadata() .setProducerName("default"); builder.setSchemaVersion(new byte[10]); @@ -248,7 +248,7 @@ public void testSeparatedAVROVersionGetProducerDataAssigned() { SchemaTestUtils.Bar bar = new SchemaTestUtils.Bar(); bar.setField1(true); - byte[] encodeBytes = keyValueSchema.encode(new KeyValue(foo, bar)); + byte[] encodeBytes = keyValueSchema.encode(new KeyValue<>(foo, bar)); MessageMetadata builder = new MessageMetadata() .setProducerName("separated"); builder.setSchemaVersion(new byte[10]); @@ -286,7 +286,7 @@ public void testDefaultJSONVersionGetProducerDataAssigned() { SchemaTestUtils.Bar bar = new SchemaTestUtils.Bar(); bar.setField1(true); - byte[] encodeBytes = keyValueSchema.encode(new KeyValue(foo, bar)); + byte[] encodeBytes = keyValueSchema.encode(new KeyValue<>(foo, bar)); MessageMetadata builder = new MessageMetadata() .setProducerName("default"); builder.setSchemaVersion(new byte[10]); @@ -322,7 +322,7 @@ public void testSeparatedJSONVersionGetProducerDataAssigned() { SchemaTestUtils.Bar bar = new SchemaTestUtils.Bar(); bar.setField1(true); - byte[] encodeBytes = keyValueSchema.encode(new KeyValue(foo, bar)); + byte[] encodeBytes = keyValueSchema.encode(new KeyValue<>(foo, bar)); MessageMetadata builder = new MessageMetadata() .setProducerName("separated"); builder.setSchemaVersion(new byte[10]); @@ -360,7 +360,7 @@ public void testDefaultAVROJSONVersionGetProducerDataAssigned() { SchemaTestUtils.Bar bar = new SchemaTestUtils.Bar(); bar.setField1(true); - byte[] encodeBytes = keyValueSchema.encode(new KeyValue(foo, bar)); + byte[] encodeBytes = keyValueSchema.encode(new KeyValue<>(foo, bar)); MessageMetadata builder = new MessageMetadata() .setProducerName("default"); builder.setSchemaVersion(new byte[10]); @@ -396,7 +396,7 @@ public void testSeparatedAVROJSONVersionGetProducerDataAssigned() { SchemaTestUtils.Bar bar = new SchemaTestUtils.Bar(); bar.setField1(true); - byte[] encodeBytes = keyValueSchema.encode(new KeyValue(foo, bar)); + byte[] encodeBytes = keyValueSchema.encode(new KeyValue<>(foo, bar)); MessageMetadata builder = new MessageMetadata() .setProducerName("separated"); builder.setSchemaVersion(new byte[10]); diff --git a/pulsar-client/src/test/java/org/apache/pulsar/client/impl/MultiTopicsConsumerImplTest.java b/pulsar-client/src/test/java/org/apache/pulsar/client/impl/MultiTopicsConsumerImplTest.java index 54175613e3bb8..f5c85780f6159 100644 --- a/pulsar-client/src/test/java/org/apache/pulsar/client/impl/MultiTopicsConsumerImplTest.java +++ b/pulsar-client/src/test/java/org/apache/pulsar/client/impl/MultiTopicsConsumerImplTest.java @@ -107,11 +107,13 @@ public void testGetStats() throws Exception { @Cleanup PulsarClientImpl clientImpl = new PulsarClientImpl(conf, eventLoopGroup); + @SuppressWarnings("rawtypes") ConsumerConfigurationData consumerConfData = new ConsumerConfigurationData(); consumerConfData.setTopicNames(Sets.newHashSet(topicName)); assertEquals(Long.parseLong("100"), clientImpl.getConfiguration().getStatsIntervalSeconds()); + @SuppressWarnings("rawtypes") MultiTopicsConsumerImpl impl = new MultiTopicsConsumerImpl( clientImpl, consumerConfData, executorProvider, null, Schema.BYTES, null, true); diff --git a/pulsar-client/src/test/java/org/apache/pulsar/client/impl/PartitionedProducerImplTest.java b/pulsar-client/src/test/java/org/apache/pulsar/client/impl/PartitionedProducerImplTest.java index ce2c200344d96..34faceaff81ad 100644 --- a/pulsar-client/src/test/java/org/apache/pulsar/client/impl/PartitionedProducerImplTest.java +++ b/pulsar-client/src/test/java/org/apache/pulsar/client/impl/PartitionedProducerImplTest.java @@ -65,12 +65,16 @@ public class PartitionedProducerImplTest { private static final String TOPIC_NAME = "testTopicName"; private PulsarClientImpl client; + @SuppressWarnings("rawtypes") private ProducerBuilderImpl producerBuilderImpl; + @SuppressWarnings("rawtypes") private Schema schema; private ProducerInterceptors producerInterceptors; - private CompletableFuture producerCreatedFuture; + @SuppressWarnings("rawtypes") + private CompletableFuture producerCreatedFuture; @BeforeMethod(alwaysRun = true) + @SuppressWarnings("rawtypes") public void setup() { client = mock(PulsarClientImpl.class); ConnectionPool connectionPool = mock(ConnectionPool.class); @@ -164,6 +168,7 @@ public void testPartialPartitionWithKey() { assertNotEquals(actualHashList, expectedHashList); } + @SuppressWarnings("rawtypes") private MessageRouter getMessageRouter(ProducerConfigurationData producerConfigurationData) throws NoSuchFieldException, IllegalAccessException { PartitionedProducerImpl impl = new PartitionedProducerImpl( @@ -205,7 +210,7 @@ public void testGetStats() throws Exception { assertEquals(Long.parseLong("100"), clientImpl.getConfiguration().getStatsIntervalSeconds()); - PartitionedProducerImpl impl = new PartitionedProducerImpl( + PartitionedProducerImpl impl = new PartitionedProducerImpl<>( clientImpl, topicName, producerConfData, 1, null, null, null); @@ -265,14 +270,14 @@ public void testGetNumOfPartitions() throws Exception { producerConfData.setMessageRoutingMode(MessageRoutingMode.CustomPartition); producerConfData.setCustomMessageRouter(new CustomMessageRouter()); - PartitionedProducerImpl partitionedProducerImpl = new PartitionedProducerImpl( + PartitionedProducerImpl partitionedProducerImpl = new PartitionedProducerImpl<>( clientImpl, topicName, producerConfData, 1, null, null, null); assertEquals(partitionedProducerImpl.getNumOfPartitions(), 1); String nonPartitionedTopicName = "test-get-num-of-partitions-for-non-partitioned-topic"; ProducerConfigurationData producerConfDataNonPartitioned = new ProducerConfigurationData(); - ProducerImpl producerImpl = new ProducerImpl(clientImpl, nonPartitionedTopicName, + ProducerImpl producerImpl = new ProducerImpl<>(clientImpl, nonPartitionedTopicName, producerConfDataNonPartitioned, null, 0, null, null, Optional.empty()); assertEquals(producerImpl.getNumOfPartitions(), 0); } @@ -296,21 +301,21 @@ public void testMaxPendingQueueSize() throws Exception { producerConfData.setMessageRoutingMode(MessageRoutingMode.CustomPartition); producerConfData.setCustomMessageRouter(new CustomMessageRouter()); producerConfData.setMaxPendingMessages(10); - PartitionedProducerImpl partitionedProducerImpl = new PartitionedProducerImpl( + PartitionedProducerImpl partitionedProducerImpl = new PartitionedProducerImpl<>( clientImpl, topicName, producerConfData, 1, null, null, null); assertEquals(partitionedProducerImpl.getConfiguration().getMaxPendingMessages(), 10); // Test set MaxPendingMessagesAcrossPartitions=5 producerConfData.setMaxPendingMessages(ProducerConfigurationData.DEFAULT_MAX_PENDING_MESSAGES); producerConfData.setMaxPendingMessagesAcrossPartitions(5); - partitionedProducerImpl = new PartitionedProducerImpl( + partitionedProducerImpl = new PartitionedProducerImpl<>( clientImpl, topicName, producerConfData, 1, null, null, null); assertEquals(partitionedProducerImpl.getConfiguration().getMaxPendingMessages(), 5); // Test set maxPendingMessage=10 and MaxPendingMessagesAcrossPartitions=10 with 2 partitions producerConfData.setMaxPendingMessages(10); producerConfData.setMaxPendingMessagesAcrossPartitions(10); - partitionedProducerImpl = new PartitionedProducerImpl( + partitionedProducerImpl = new PartitionedProducerImpl<>( clientImpl, topicName, producerConfData, 2, null, null, null); assertEquals(partitionedProducerImpl.getConfiguration().getMaxPendingMessages(), 5); } @@ -334,12 +339,12 @@ public void testOnTopicsExtended() throws Exception { producerConfData.setCustomMessageRouter(new CustomMessageRouter()); producerConfData.setAutoUpdatePartitionsIntervalSeconds(1, TimeUnit.MILLISECONDS); - PartitionedProducerImpl impl = new PartitionedProducerImpl( + PartitionedProducerImpl impl = new PartitionedProducerImpl<>( clientImpl, topicName, producerConfData, 1, null, null, null); impl.setState(HandlerState.State.Ready); Thread.sleep(1000); - CompletableFuture future = impl.getPartitionsAutoUpdateFuture(); + CompletableFuture future = impl.getPartitionsAutoUpdateFuture(); // When null is returned in method thenCompose we will encounter an NPE exception. // Because the returned value will be applied to the next stage. diff --git a/pulsar-client/src/test/java/org/apache/pulsar/client/impl/PatternConsumerUpdateQueueTest.java b/pulsar-client/src/test/java/org/apache/pulsar/client/impl/PatternConsumerUpdateQueueTest.java index e8294eb94c028..fd47d6e6cea7b 100644 --- a/pulsar-client/src/test/java/org/apache/pulsar/client/impl/PatternConsumerUpdateQueueTest.java +++ b/pulsar-client/src/test/java/org/apache/pulsar/client/impl/PatternConsumerUpdateQueueTest.java @@ -50,6 +50,7 @@ private QueueInstance createInstance(CompletableFuture customizedRecheckFu null, null); } + @SuppressWarnings("rawtypes") private QueueInstance createInstance(CompletableFuture customizedRecheckFuture, CompletableFuture customizedPartialUpdateFuture, CompletableFuture customizedConsumerInitFuture, @@ -77,8 +78,8 @@ private QueueInstance createInstance(CompletableFuture customizedRecheckFu when(topicsChangeListener.onTopicsRemoved(anyCollection())).thenReturn(customizedPartialUpdateFuture); } else { CompletableFuture ex = FutureUtil.failedFuture(new RuntimeException("Failed topics changed event")); - Answer answer = invocationOnMock -> { - Collection inputCollection = invocationOnMock.getArgument(0, Collection.class); + Answer answer = invocationOnMock -> { + Collection inputCollection = invocationOnMock.getArgument(0, Collection.class); if (successTopics.containsAll(inputCollection)) { return customizedPartialUpdateFuture; } else if (errorTopics.containsAll(inputCollection)) { @@ -103,7 +104,7 @@ private QueueInstance createInstance() { @AllArgsConstructor private static class QueueInstance implements Closeable { private PatternConsumerUpdateQueue queue; - private PatternMultiTopicsConsumerImpl mockedConsumer; + private PatternMultiTopicsConsumerImpl mockedConsumer; private PatternMultiTopicsConsumerImpl.TopicsChangedListener mockedListener; @Override diff --git a/pulsar-client/src/test/java/org/apache/pulsar/client/impl/TableViewBuilderImplTest.java b/pulsar-client/src/test/java/org/apache/pulsar/client/impl/TableViewBuilderImplTest.java index e2becec1105ec..8f9ad0d5c886f 100644 --- a/pulsar-client/src/test/java/org/apache/pulsar/client/impl/TableViewBuilderImplTest.java +++ b/pulsar-client/src/test/java/org/apache/pulsar/client/impl/TableViewBuilderImplTest.java @@ -44,13 +44,13 @@ public class TableViewBuilderImplTest { private static final String TOPIC_NAME = "testTopicName"; private PulsarClientImpl client; - private TableViewBuilderImpl tableViewBuilderImpl; + private TableViewBuilderImpl tableViewBuilderImpl; private CompletableFuture readNextFuture; @BeforeClass(alwaysRun = true) public void setup() { - Reader reader = mock(Reader.class); - readNextFuture = new CompletableFuture(); + Reader reader = mock(Reader.class); + readNextFuture = new CompletableFuture<>(); when(reader.readNextAsync()).thenReturn(readNextFuture); client = mock(PulsarClientImpl.class); ConnectionPool connectionPool = mock(ConnectionPool.class); @@ -72,7 +72,7 @@ public void cleanup() { @Test public void testTableViewBuilderImpl() throws PulsarClientException { - TableView tableView = tableViewBuilderImpl.topic(TOPIC_NAME) + TableView tableView = tableViewBuilderImpl.topic(TOPIC_NAME) .autoUpdatePartitionsInterval(5, TimeUnit.SECONDS) .subscriptionName("testSubscriptionName") .cryptoKeyReader(mock(CryptoKeyReader.class)) @@ -84,7 +84,7 @@ public void testTableViewBuilderImpl() throws PulsarClientException { @Test public void testTableViewBuilderImplWhenOnlyTopicNameIsSet() throws PulsarClientException { - TableView tableView = tableViewBuilderImpl.topic(TOPIC_NAME) + TableView tableView = tableViewBuilderImpl.topic(TOPIC_NAME) .create(); assertNotNull(tableView); @@ -118,7 +118,7 @@ public void testTableViewBuilderImplWhenSubscriptionNameIsEmptyString() throws P @Test public void testTableViewBuilderImplWithCryptoKeyReader() throws PulsarClientException { - TableView tableView = tableViewBuilderImpl.topic(TOPIC_NAME) + TableView tableView = tableViewBuilderImpl.topic(TOPIC_NAME) .cryptoKeyReader(mock(CryptoKeyReader.class)) .create(); diff --git a/pulsar-client/src/test/java/org/apache/pulsar/client/impl/TableViewImplTest.java b/pulsar-client/src/test/java/org/apache/pulsar/client/impl/TableViewImplTest.java index c1ab9ae6b62ee..0a682eee589c3 100644 --- a/pulsar-client/src/test/java/org/apache/pulsar/client/impl/TableViewImplTest.java +++ b/pulsar-client/src/test/java/org/apache/pulsar/client/impl/TableViewImplTest.java @@ -48,7 +48,7 @@ public void setup() { @Test public void testTableViewImpl() { data.setCryptoKeyReader(mock(CryptoKeyReader.class)); - TableView tableView = new TableViewImpl(client, Schema.BYTES, data); + TableView tableView = new TableViewImpl<>(client, Schema.BYTES, data); assertNotNull(tableView); } diff --git a/pulsar-client/src/test/java/org/apache/pulsar/client/impl/TypedMessageBuilderImplTest.java b/pulsar-client/src/test/java/org/apache/pulsar/client/impl/TypedMessageBuilderImplTest.java index 257fc6885b76c..3d0cae19196c2 100644 --- a/pulsar-client/src/test/java/org/apache/pulsar/client/impl/TypedMessageBuilderImplTest.java +++ b/pulsar-client/src/test/java/org/apache/pulsar/client/impl/TypedMessageBuilderImplTest.java @@ -42,7 +42,7 @@ public class TypedMessageBuilderImplTest { @Mock - protected ProducerBase producerBase; + protected ProducerBase producerBase; @Test public void testDefaultValue() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { @@ -55,6 +55,7 @@ public void testDefaultValue() throws NoSuchMethodException, InvocationTargetExc Schema> keyValueSchema = Schema.KeyValue(fooSchema, barSchema); + @SuppressWarnings("rawtypes") TypedMessageBuilderImpl typedMessageBuilderImpl = new TypedMessageBuilderImpl(producerBase, keyValueSchema); SchemaTestUtils.Foo foo = new SchemaTestUtils.Foo(); @@ -65,8 +66,8 @@ public void testDefaultValue() throws NoSuchMethodException, InvocationTargetExc KeyValue keyValue = new KeyValue<>(foo, bar); // Check kv.encoding.type default, not set value - TypedMessageBuilderImpl typedMessageBuilder = - (TypedMessageBuilderImpl) typedMessageBuilderImpl.value(keyValue); + TypedMessageBuilderImpl> typedMessageBuilder = + (TypedMessageBuilderImpl>) typedMessageBuilderImpl.value(keyValue); Method method = TypedMessageBuilderImpl.class.getDeclaredMethod("beforeSend"); method.setAccessible(true); method.invoke(typedMessageBuilder); @@ -90,7 +91,8 @@ public void testInlineValue() throws NoSuchMethodException, InvocationTargetExce Schema> keyValueSchema = Schema.KeyValue(fooSchema, barSchema, KeyValueEncodingType.INLINE); - TypedMessageBuilderImpl typedMessageBuilderImpl = new TypedMessageBuilderImpl (producerBase, keyValueSchema); + @SuppressWarnings("rawtypes") + TypedMessageBuilderImpl typedMessageBuilderImpl = new TypedMessageBuilderImpl(producerBase, keyValueSchema); SchemaTestUtils.Foo foo = new SchemaTestUtils.Foo(); foo.setField1("field1"); @@ -100,8 +102,8 @@ public void testInlineValue() throws NoSuchMethodException, InvocationTargetExce KeyValue keyValue = new KeyValue<>(foo, bar); // Check kv.encoding.type INLINE - TypedMessageBuilderImpl typedMessageBuilder = - (TypedMessageBuilderImpl) typedMessageBuilderImpl.value(keyValue); + TypedMessageBuilderImpl> typedMessageBuilder = + (TypedMessageBuilderImpl>) typedMessageBuilderImpl.value(keyValue); Method method = TypedMessageBuilderImpl.class.getDeclaredMethod("beforeSend"); method.setAccessible(true); method.invoke(typedMessageBuilder); @@ -125,7 +127,8 @@ public void testSeparatedValue() throws Exception { Schema> keyValueSchema = Schema.KeyValue(fooSchema, barSchema, KeyValueEncodingType.SEPARATED); - TypedMessageBuilderImpl typedMessageBuilderImpl = new TypedMessageBuilderImpl (producerBase, keyValueSchema); + @SuppressWarnings("rawtypes") + TypedMessageBuilderImpl typedMessageBuilderImpl = new TypedMessageBuilderImpl(producerBase, keyValueSchema); SchemaTestUtils.Foo foo = new SchemaTestUtils.Foo(); foo.setField1("field1"); @@ -135,7 +138,7 @@ public void testSeparatedValue() throws Exception { KeyValue keyValue = new KeyValue<>(foo, bar); // Check kv.encoding.type SEPARATED - TypedMessageBuilderImpl typedMessageBuilder = (TypedMessageBuilderImpl) typedMessageBuilderImpl.value(keyValue); + TypedMessageBuilderImpl typedMessageBuilder = (TypedMessageBuilderImpl) typedMessageBuilderImpl.value(keyValue); Method method = TypedMessageBuilderImpl.class.getDeclaredMethod("beforeSend"); method.setAccessible(true); method.invoke(typedMessageBuilder); @@ -159,10 +162,11 @@ public void testSetKeyEncodingTypeDefault() { Schema> keyValueSchema = Schema.KeyValue(fooSchema, barSchema); + @SuppressWarnings("rawtypes") TypedMessageBuilderImpl typedMessageBuilderImpl = new TypedMessageBuilderImpl(producerBase, keyValueSchema); - TypedMessageBuilderImpl typedMessageBuilder = - (TypedMessageBuilderImpl) typedMessageBuilderImpl.key("default"); + TypedMessageBuilderImpl typedMessageBuilder = + (TypedMessageBuilderImpl) typedMessageBuilderImpl.key("default"); assertEquals(typedMessageBuilder.getKey(), "default"); assertFalse(typedMessageBuilder.getMetadataBuilder().isPartitionKeyB64Encoded()); } @@ -178,10 +182,11 @@ public void testSetKeyEncodingTypeInline() { Schema> keyValueSchema = Schema.KeyValue(fooSchema, barSchema, KeyValueEncodingType.INLINE); + @SuppressWarnings("rawtypes") TypedMessageBuilderImpl typedMessageBuilderImpl = new TypedMessageBuilderImpl(producerBase, keyValueSchema); - TypedMessageBuilderImpl typedMessageBuilder = - (TypedMessageBuilderImpl) typedMessageBuilderImpl.key("inline"); + TypedMessageBuilderImpl typedMessageBuilder = + (TypedMessageBuilderImpl) typedMessageBuilderImpl.key("inline"); assertEquals(typedMessageBuilder.getKey(), "inline"); assertFalse(typedMessageBuilder.getMetadataBuilder().isPartitionKeyB64Encoded()); } @@ -197,12 +202,13 @@ public void testSetKeyEncodingTypeSeparated() { Schema> keyValueSchema = Schema.KeyValue(fooSchema, barSchema, KeyValueEncodingType.SEPARATED); + @SuppressWarnings("rawtypes") TypedMessageBuilderImpl typedMessageBuilderImpl = new TypedMessageBuilderImpl(producerBase, keyValueSchema); try { - TypedMessageBuilderImpl typedMessageBuilder = - (TypedMessageBuilderImpl) typedMessageBuilderImpl.key("separated"); + TypedMessageBuilderImpl typedMessageBuilder = + (TypedMessageBuilderImpl) typedMessageBuilderImpl.key("separated"); fail("This should fail"); } catch (IllegalArgumentException e) { assertTrue(e.getMessage() @@ -221,10 +227,11 @@ public void testSetKeyBytesEncodingTypeDefault() { Schema> keyValueSchema = Schema.KeyValue(fooSchema, barSchema); + @SuppressWarnings("rawtypes") TypedMessageBuilderImpl typedMessageBuilderImpl = new TypedMessageBuilderImpl(producerBase, keyValueSchema); - TypedMessageBuilderImpl typedMessageBuilder = - (TypedMessageBuilderImpl) typedMessageBuilderImpl.keyBytes("default".getBytes()); + TypedMessageBuilderImpl typedMessageBuilder = + (TypedMessageBuilderImpl) typedMessageBuilderImpl.keyBytes("default".getBytes()); assertEquals(typedMessageBuilder.getKey(), Base64.getEncoder().encodeToString("default".getBytes())); assertTrue(typedMessageBuilder.getMetadataBuilder().isPartitionKeyB64Encoded()); } @@ -240,10 +247,11 @@ public void testSetKeyBytesEncodingTypeInline() { Schema> keyValueSchema = Schema.KeyValue(fooSchema, barSchema, KeyValueEncodingType.INLINE); + @SuppressWarnings("rawtypes") TypedMessageBuilderImpl typedMessageBuilderImpl = new TypedMessageBuilderImpl(producerBase, keyValueSchema); - TypedMessageBuilderImpl typedMessageBuilder = - (TypedMessageBuilderImpl) typedMessageBuilderImpl.keyBytes("inline".getBytes()); + TypedMessageBuilderImpl typedMessageBuilder = + (TypedMessageBuilderImpl) typedMessageBuilderImpl.keyBytes("inline".getBytes()); assertEquals(typedMessageBuilder.getKey(), Base64.getEncoder().encodeToString("inline".getBytes())); assertTrue(typedMessageBuilder.getMetadataBuilder().isPartitionKeyB64Encoded()); } @@ -259,12 +267,13 @@ public void testSetKeyBytesEncodingTypeSeparated() { Schema> keyValueSchema = Schema.KeyValue(fooSchema, barSchema, KeyValueEncodingType.SEPARATED); + @SuppressWarnings("rawtypes") TypedMessageBuilderImpl typedMessageBuilderImpl = new TypedMessageBuilderImpl(producerBase, keyValueSchema); try { - TypedMessageBuilderImpl typedMessageBuilder = - (TypedMessageBuilderImpl) typedMessageBuilderImpl.keyBytes("separated".getBytes()); + TypedMessageBuilderImpl typedMessageBuilder = + (TypedMessageBuilderImpl) typedMessageBuilderImpl.keyBytes("separated".getBytes()); fail("This should fail"); } catch (IllegalArgumentException e) { assertTrue(e.getMessage() diff --git a/pulsar-client/src/test/java/org/apache/pulsar/client/impl/conf/ConfigurationDataUtilsTest.java b/pulsar-client/src/test/java/org/apache/pulsar/client/impl/conf/ConfigurationDataUtilsTest.java index 9ca0c2d81b7e5..cc04220c839ca 100644 --- a/pulsar-client/src/test/java/org/apache/pulsar/client/impl/conf/ConfigurationDataUtilsTest.java +++ b/pulsar-client/src/test/java/org/apache/pulsar/client/impl/conf/ConfigurationDataUtilsTest.java @@ -100,7 +100,7 @@ public void testLoadProducerConfigurationData() { @Test public void testLoadConsumerConfigurationData() { - ConsumerConfigurationData confData = new ConsumerConfigurationData(); + ConsumerConfigurationData confData = new ConsumerConfigurationData(); confData.setSubscriptionName("unknown-subscription"); confData.setPriorityLevel(10000); confData.setConsumerName("unknown-consumer"); @@ -117,7 +117,7 @@ public void testLoadConsumerConfigurationData() { @Test public void testLoadReaderConfigurationData() { - ReaderConfigurationData confData = new ReaderConfigurationData(); + ReaderConfigurationData confData = new ReaderConfigurationData(); confData.setTopicName("unknown"); confData.setReceiverQueueSize(1000000); confData.setReaderName("unknown-reader"); @@ -132,7 +132,7 @@ public void testLoadReaderConfigurationData() { @Test public void testLoadConfigurationDataWithUnknownFields() { - ReaderConfigurationData confData = new ReaderConfigurationData(); + ReaderConfigurationData confData = new ReaderConfigurationData(); confData.setTopicName("unknown"); confData.setReceiverQueueSize(1000000); confData.setReaderName("unknown-reader"); diff --git a/pulsar-client/src/test/java/org/apache/pulsar/client/impl/schema/KeyValueSchemaInfoTest.java b/pulsar-client/src/test/java/org/apache/pulsar/client/impl/schema/KeyValueSchemaInfoTest.java index 97019ec93d6d9..b6b4db7bb88e0 100644 --- a/pulsar-client/src/test/java/org/apache/pulsar/client/impl/schema/KeyValueSchemaInfoTest.java +++ b/pulsar-client/src/test/java/org/apache/pulsar/client/impl/schema/KeyValueSchemaInfoTest.java @@ -46,7 +46,7 @@ @Slf4j public class KeyValueSchemaInfoTest { - private static final Map FOO_PROPERTIES = new HashMap() { + private static final Map FOO_PROPERTIES = new HashMap<>() { private static final long serialVersionUID = 58641844834472929L; @@ -58,7 +58,7 @@ public class KeyValueSchemaInfoTest { }; - private static final Map BAR_PROPERTIES = new HashMap() { + private static final Map BAR_PROPERTIES = new HashMap<>() { private static final long serialVersionUID = 58641844834472929L; diff --git a/pulsar-client/src/test/java/org/apache/pulsar/client/impl/schema/KeyValueSchemaTest.java b/pulsar-client/src/test/java/org/apache/pulsar/client/impl/schema/KeyValueSchemaTest.java index 6de7f805f93bf..43ddd85af2a6d 100644 --- a/pulsar-client/src/test/java/org/apache/pulsar/client/impl/schema/KeyValueSchemaTest.java +++ b/pulsar-client/src/test/java/org/apache/pulsar/client/impl/schema/KeyValueSchemaTest.java @@ -249,7 +249,7 @@ public void testAllowNullSchemaEncodeAndDecode() { foo.setField4(bar); foo.setColor(Color.RED); - byte[] encodeBytes = keyValueSchema.encode(new KeyValue(foo, bar)); + byte[] encodeBytes = keyValueSchema.encode(new KeyValue<>(foo, bar)); Assert.assertTrue(encodeBytes.length > 0); KeyValue keyValue = (KeyValue) keyValueSchema.decode(encodeBytes); @@ -277,7 +277,7 @@ public void testNotAllowNullSchemaEncodeAndDecode() { foo.setField4(bar); foo.setColor(Color.RED); - byte[] encodeBytes = keyValueSchema.encode(new KeyValue(foo, bar)); + byte[] encodeBytes = keyValueSchema.encode(new KeyValue<>(foo, bar)); Assert.assertTrue(encodeBytes.length > 0); KeyValue keyValue = (KeyValue) keyValueSchema.decode(encodeBytes); @@ -306,7 +306,7 @@ public void testDefaultKeyValueEncodingTypeSchemaEncodeAndDecode() { foo.setColor(Color.RED); // Check kv.encoding.type default not set value - byte[] encodeBytes = keyValueSchema.encode(new KeyValue(foo, bar)); + byte[] encodeBytes = keyValueSchema.encode(new KeyValue<>(foo, bar)); Assert.assertTrue(encodeBytes.length > 0); KeyValue keyValue = (KeyValue) keyValueSchema.decode(encodeBytes); @@ -338,7 +338,7 @@ public void testInlineKeyValueEncodingTypeSchemaEncodeAndDecode() { foo.setColor(Color.RED); // Check kv.encoding.type INLINE - byte[] encodeBytes = keyValueSchema.encode(new KeyValue(foo, bar)); + byte[] encodeBytes = keyValueSchema.encode(new KeyValue<>(foo, bar)); Assert.assertTrue(encodeBytes.length > 0); KeyValue keyValue = (KeyValue) keyValueSchema.decode(encodeBytes); Foo fooBack = keyValue.getKey(); @@ -367,7 +367,7 @@ public void testSeparatedKeyValueEncodingTypeSchemaEncodeAndDecode() { foo.setColor(Color.RED); // Check kv.encoding.type SEPARATED - byte[] encodeBytes = keyValueSchema.encode(new KeyValue(foo, bar)); + byte[] encodeBytes = keyValueSchema.encode(new KeyValue<>(foo, bar)); Assert.assertTrue(encodeBytes.length > 0); try { keyValueSchema.decode(encodeBytes); diff --git a/pulsar-client/src/test/java/org/apache/pulsar/client/impl/schema/PrimitiveSchemaTest.java b/pulsar-client/src/test/java/org/apache/pulsar/client/impl/schema/PrimitiveSchemaTest.java index af46aa5318547..202d17cfc3593 100644 --- a/pulsar-client/src/test/java/org/apache/pulsar/client/impl/schema/PrimitiveSchemaTest.java +++ b/pulsar-client/src/test/java/org/apache/pulsar/client/impl/schema/PrimitiveSchemaTest.java @@ -55,7 +55,7 @@ public Object[][] schemas() { // we are not using a static initialization block, see here: // https://github.com/apache/pulsar/issues/11037 - final Map> testData = new HashMap() { + final Map, List> testData = new HashMap<>() { { put(BooleanSchema.of(), Arrays.asList(false, true)); put(StringSchema.utf8(), Arrays.asList("my string")); @@ -82,7 +82,7 @@ public Object[][] schemas() { } }; - final Map> testData2 = new HashMap() { + final Map, List> testData2 = new HashMap<>() { { put(Schema.BOOL, Arrays.asList(false, true)); put(Schema.STRING, Arrays.asList("my string")); @@ -108,10 +108,10 @@ public Object[][] schemas() { } }; - for (Schema schema : testData.keySet()) { + for (Schema schema : testData.keySet()) { assertNotNull(schema); } - for (Schema schema : testData2.keySet()) { + for (Schema schema : testData2.keySet()) { assertNotNull(schema); } @@ -119,7 +119,7 @@ public Object[][] schemas() { } @Test(dataProvider = "schemas") - public void allSchemasShouldSupportNull(Map> testData) { + public void allSchemasShouldSupportNull(Map, List> testData) { for (Schema schema : testData.keySet()) { byte[] bytes = null; ByteBuf byteBuf = null; @@ -137,6 +137,7 @@ public void allSchemasShouldSupportNull(Map> testData) { } @Test(dataProvider = "schemas") + @SuppressWarnings("rawtypes") public void allSchemasShouldRoundtripInput(Map> testData) { for (Map.Entry> test : testData.entrySet()) { log.info("Test schema {}", test.getKey()); diff --git a/pulsar-client/src/test/java/org/apache/pulsar/client/impl/schema/SchemaBuilderTest.java b/pulsar-client/src/test/java/org/apache/pulsar/client/impl/schema/SchemaBuilderTest.java index 70c4541be9d6d..dfdcbc8470c79 100644 --- a/pulsar-client/src/test/java/org/apache/pulsar/client/impl/schema/SchemaBuilderTest.java +++ b/pulsar-client/src/test/java/org/apache/pulsar/client/impl/schema/SchemaBuilderTest.java @@ -164,6 +164,7 @@ public void testGenericRecordBuilderByFieldName() { SchemaInfo schemaInfo = recordSchemaBuilder.build( SchemaType.AVRO ); + @SuppressWarnings("rawtypes") GenericSchema schema = Schema.generic(schemaInfo); GenericRecord record = schema.newRecordBuilder() .set("intField", 32) @@ -503,7 +504,7 @@ public void testGenericRecordBuilderAvroByFieldIndexPojo() { * @param decoder the schema used for reading * @param writer the schema used for writing */ - private static void injectWriterSchema(Schema decoder, Schema writer) { + private static void injectWriterSchema(Schema decoder, Schema writer) { AvroSchema avroSchema = (AvroSchema) decoder; avroSchema.setReader(new MultiVersionAvroReader<>( AvroSchema.of(SchemaDefinition. diff --git a/pulsar-client/src/test/java/org/apache/pulsar/client/impl/schema/SupportVersioningAvroSchemaTest.java b/pulsar-client/src/test/java/org/apache/pulsar/client/impl/schema/SupportVersioningAvroSchemaTest.java index dbac3ae1d21f4..14464a3838f76 100644 --- a/pulsar-client/src/test/java/org/apache/pulsar/client/impl/schema/SupportVersioningAvroSchemaTest.java +++ b/pulsar-client/src/test/java/org/apache/pulsar/client/impl/schema/SupportVersioningAvroSchemaTest.java @@ -33,7 +33,7 @@ public class SupportVersioningAvroSchemaTest { private MultiVersionSchemaInfoProvider multiVersionSchemaInfoProvider; - private AvroSchema schema; + private AvroSchema schema; private GenericAvroSchema genericAvroSchema; private AvroSchema avroFooV2Schema; diff --git a/pulsar-client/src/test/java/org/apache/pulsar/client/impl/schema/SupportVersioningKeyValueSchemaTest.java b/pulsar-client/src/test/java/org/apache/pulsar/client/impl/schema/SupportVersioningKeyValueSchemaTest.java index f64e7a9162490..8e4b0b0bea79a 100644 --- a/pulsar-client/src/test/java/org/apache/pulsar/client/impl/schema/SupportVersioningKeyValueSchemaTest.java +++ b/pulsar-client/src/test/java/org/apache/pulsar/client/impl/schema/SupportVersioningKeyValueSchemaTest.java @@ -56,7 +56,7 @@ public void testKeyValueVersioningEncodeDecode() { foo.setField4(bar); foo.setColor(SchemaTestUtils.Color.RED); - byte[] encodeBytes = keyValueSchema.encode(new KeyValue(foo, bar)); + byte[] encodeBytes = keyValueSchema.encode(new KeyValue<>(foo, bar)); KeyValue keyValue = keyValueSchema.decode( encodeBytes, new byte[10]); Assert.assertEquals(keyValue.getKey().getField1(), foo.getField1()); @@ -94,7 +94,7 @@ public void testSeparateKeyValueVersioningEncodeDecode() { foo.setField4(bar); foo.setColor(SchemaTestUtils.Color.RED); - byte[] encodeBytes = keyValueSchema.encode(new KeyValue(foo, bar)); + byte[] encodeBytes = keyValueSchema.encode(new KeyValue<>(foo, bar)); KeyValue keyValue = ((KeyValueSchemaImpl) keyValueSchema).decode( fooSchema.encode(foo), encodeBytes, new byte[10]); Assert.assertTrue(keyValue.getValue().isField1()); @@ -122,7 +122,7 @@ public void testKeyValueDefaultVersioningEncodeDecode() { foo.setField4(bar); foo.setColor(SchemaTestUtils.Color.RED); - byte[] encodeBytes = keyValueSchema.encode(new KeyValue(foo, bar)); + byte[] encodeBytes = keyValueSchema.encode(new KeyValue<>(foo, bar)); KeyValue keyValue = keyValueSchema.decode( encodeBytes, new byte[10]); Assert.assertEquals(keyValue.getKey().getField1(), foo.getField1()); @@ -155,7 +155,7 @@ public void testKeyValueLatestVersioningEncodeDecode() { foo.setField4(bar); foo.setColor(SchemaTestUtils.Color.RED); - byte[] encodeBytes = keyValueSchema.encode(new KeyValue(foo, bar)); + byte[] encodeBytes = keyValueSchema.encode(new KeyValue<>(foo, bar)); KeyValue keyValue = ((KeyValueSchemaImpl) keyValueSchema).decode( fooSchema.encode(foo), encodeBytes, new byte[10]); Assert.assertTrue(keyValue.getValue().isField1()); diff --git a/pulsar-client/src/test/java/org/apache/pulsar/client/impl/schema/generic/GenericAvroReaderTest.java b/pulsar-client/src/test/java/org/apache/pulsar/client/impl/schema/generic/GenericAvroReaderTest.java index 21fc90bf94776..1cc611b4226b2 100644 --- a/pulsar-client/src/test/java/org/apache/pulsar/client/impl/schema/generic/GenericAvroReaderTest.java +++ b/pulsar-client/src/test/java/org/apache/pulsar/client/impl/schema/generic/GenericAvroReaderTest.java @@ -36,9 +36,13 @@ public class GenericAvroReaderTest { private Foo foo; private FooV2 fooV2; + @SuppressWarnings("rawtypes") private AvroSchema fooSchemaNotNull; + @SuppressWarnings("rawtypes") private AvroSchema fooSchema; + @SuppressWarnings("rawtypes") private AvroSchema fooV2Schema; + @SuppressWarnings("rawtypes") private AvroSchema fooOffsetSchema; @BeforeMethod diff --git a/pulsar-client/src/test/java/org/apache/pulsar/client/impl/schema/generic/GenericProtobufNativeReaderTest.java b/pulsar-client/src/test/java/org/apache/pulsar/client/impl/schema/generic/GenericProtobufNativeReaderTest.java index 5bc147cb0e3fd..ed13a3d768efe 100644 --- a/pulsar-client/src/test/java/org/apache/pulsar/client/impl/schema/generic/GenericProtobufNativeReaderTest.java +++ b/pulsar-client/src/test/java/org/apache/pulsar/client/impl/schema/generic/GenericProtobufNativeReaderTest.java @@ -37,7 +37,7 @@ public class GenericProtobufNativeReaderTest { private TestMessage message; private GenericRecord genericmessage; private GenericProtobufNativeSchema genericProtobufNativeSchema; - private ProtobufNativeSchema clazzBasedProtobufNativeSchema; + private ProtobufNativeSchema clazzBasedProtobufNativeSchema; @BeforeMethod diff --git a/pulsar-common/src/test/java/org/apache/pulsar/common/semaphore/AsyncDualMemoryLimiterUtilTest.java b/pulsar-common/src/test/java/org/apache/pulsar/common/semaphore/AsyncDualMemoryLimiterUtilTest.java index 2f6574a74bfd5..9f9758f5cd750 100644 --- a/pulsar-common/src/test/java/org/apache/pulsar/common/semaphore/AsyncDualMemoryLimiterUtilTest.java +++ b/pulsar-common/src/test/java/org/apache/pulsar/common/semaphore/AsyncDualMemoryLimiterUtilTest.java @@ -245,7 +245,8 @@ public void testAcquireDirectMemoryPermitsAndWriteAndFlushSuccess() throws Excep }); when(channelFuture.addListener(any())).thenAnswer(invocation -> { - io.netty.util.concurrent.GenericFutureListener listener = invocation.getArgument(0); + @SuppressWarnings("unchecked") + io.netty.util.concurrent.GenericFutureListener listener = invocation.getArgument(0); listenerCalled.set(true); // Simulate successful write listener.operationComplete(channelFuture); @@ -415,13 +416,15 @@ public void testAcquireDirectMemoryPermitsAndWriteAndFlushMultipleConcurrent() t when(ctx.writeAndFlush(any(ByteBuf.class))).thenReturn(channelFuture); when(channelFuture.addListener(any())).thenAnswer(invocation -> { - io.netty.util.concurrent.GenericFutureListener listener = invocation.getArgument(0); + @SuppressWarnings("unchecked") + io.netty.util.concurrent.GenericFutureListener listener = invocation.getArgument(0); listener.operationComplete(channelFuture); return channelFuture; }); when(channelFuture.isSuccess()).thenReturn(true); int numRequests = 10; + @SuppressWarnings({"unchecked", "rawtypes"}) CompletableFuture[] futures = new CompletableFuture[numRequests]; for (int i = 0; i < numRequests; i++) { @@ -451,7 +454,8 @@ public void testAcquireDirectMemoryPermitsAndWriteAndFlushReleasesOnWriteFailure when(ctx.writeAndFlush(any(ByteBuf.class))).thenReturn(channelFuture); when(channelFuture.addListener(any())).thenAnswer(invocation -> { - io.netty.util.concurrent.GenericFutureListener listener = invocation.getArgument(0); + @SuppressWarnings("unchecked") + io.netty.util.concurrent.GenericFutureListener listener = invocation.getArgument(0); // Simulate write failure when(channelFuture.isSuccess()).thenReturn(false); when(channelFuture.cause()).thenReturn(new RuntimeException("Write to socket failed")); @@ -482,6 +486,7 @@ public void testAcquireDirectMemoryPermitsAndWriteAndFlushReleasesOnWriteFailure @Test public void testWithPermitsFutureMultipleConcurrent() throws Exception { int numOperations = 20; + @SuppressWarnings({"unchecked", "rawtypes"}) CompletableFuture[] futures = new CompletableFuture[numOperations]; AtomicInteger releaseCount = new AtomicInteger(0); diff --git a/pulsar-common/src/test/java/org/apache/pulsar/common/semaphore/AsyncSemaphoreImplTest.java b/pulsar-common/src/test/java/org/apache/pulsar/common/semaphore/AsyncSemaphoreImplTest.java index ec2e01e1a718c..6f6c86653ef19 100644 --- a/pulsar-common/src/test/java/org/apache/pulsar/common/semaphore/AsyncSemaphoreImplTest.java +++ b/pulsar-common/src/test/java/org/apache/pulsar/common/semaphore/AsyncSemaphoreImplTest.java @@ -360,7 +360,7 @@ public void testConcurrentAcquireAndRelease() throws Exception { } // Wait for all threads to complete - CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])) + CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])) .get(30, TimeUnit.SECONDS); } diff --git a/pulsar-functions/instance/src/test/java/org/apache/pulsar/functions/instance/ContextImplTest.java b/pulsar-functions/instance/src/test/java/org/apache/pulsar/functions/instance/ContextImplTest.java index 40876e57df989..4192407eff1d8 100644 --- a/pulsar-functions/instance/src/test/java/org/apache/pulsar/functions/instance/ContextImplTest.java +++ b/pulsar-functions/instance/src/test/java/org/apache/pulsar/functions/instance/ContextImplTest.java @@ -88,6 +88,7 @@ public class ContextImplTest { private PulsarClientImpl client; private PulsarAdmin pulsarAdmin; private ContextImpl context; + @SuppressWarnings("rawtypes") private Producer producer; private ProducerCache producerCache; @@ -107,9 +108,9 @@ public void setup() throws PulsarClientException { when(client.getConfiguration()).thenReturn(new ClientConfigurationData()); ConnectionPool connectionPool = mock(ConnectionPool.class); when(client.getCnxPool()).thenReturn(connectionPool); - when(client.newProducer()).thenAnswer(invocation -> new ProducerBuilderImpl(client, Schema.BYTES)); + when(client.newProducer()).thenAnswer(invocation -> new ProducerBuilderImpl<>(client, Schema.BYTES)); when(client.newProducer(any())).thenAnswer( - invocation -> new ProducerBuilderImpl(client, invocation.getArgument(0))); + invocation -> new ProducerBuilderImpl<>(client, invocation.getArgument(0))); when(client.createProducerAsync(any(ProducerConfigurationData.class), any(), any())) .thenReturn(CompletableFuture.completedFuture(producer)); when(client.getSchema(anyString())).thenReturn(CompletableFuture.completedFuture(Optional.empty())); @@ -118,6 +119,7 @@ public void setup() throws PulsarClientException { clientBuilder = mock(ClientBuilder.class); when(clientBuilder.build()).thenReturn(client); + @SuppressWarnings("rawtypes") TypedMessageBuilder messageBuilder = spy(new TypedMessageBuilderImpl(mock(ProducerBase.class), Schema.STRING)); doReturn(new CompletableFuture<>()).when(messageBuilder).sendAsync(); when(producer.newMessage()).thenReturn(messageBuilder); @@ -357,6 +359,7 @@ FunctionDetails.ComponentType.FUNCTION, null, new InstanceStateManager(), when(consumer2.getTopic()).thenReturn(TopicName.get("second").toString()); List> consumersList = Lists.newArrayList(consumer1, consumer2); + @SuppressWarnings("rawtypes") MultiTopicsConsumerImpl mtc = Mockito.mock(MultiTopicsConsumerImpl.class); when(mtc.getConsumers()).thenReturn(consumersList); diff --git a/pulsar-functions/instance/src/test/java/org/apache/pulsar/functions/instance/JavaInstanceRunnableTest.java b/pulsar-functions/instance/src/test/java/org/apache/pulsar/functions/instance/JavaInstanceRunnableTest.java index eea1c9cc96628..c9668cfc52af3 100644 --- a/pulsar-functions/instance/src/test/java/org/apache/pulsar/functions/instance/JavaInstanceRunnableTest.java +++ b/pulsar-functions/instance/src/test/java/org/apache/pulsar/functions/instance/JavaInstanceRunnableTest.java @@ -188,7 +188,7 @@ public void testFunctionAsyncTime() throws Exception { javaInstanceRunnable.setStats(manager); JavaExecutionResult javaExecutionResult = new JavaExecutionResult(); Thread.sleep(500); - Record record = mock(Record.class); + Record record = mock(Record.class); javaInstanceRunnable.handleResult(record, javaExecutionResult); ArgumentCaptor timeCaptor = ArgumentCaptor.forClass(Long.class); verify(manager).processTimeEnd(timeCaptor.capture()); @@ -200,7 +200,7 @@ public void testFunctionResultNull() throws Exception { JavaExecutionResult javaExecutionResult = new JavaExecutionResult(); // ProcessingGuarantees == MANUAL, not need ack. - Record record = mock(Record.class); + Record record = mock(Record.class); getJavaInstanceRunnable(true, org.apache.pulsar.functions.proto.Function.ProcessingGuarantees.MANUAL) .handleResult(record, javaExecutionResult); verify(record, times(0)).ack(); @@ -409,7 +409,7 @@ public void pushRecord(Record record) throws Exception { } @Override - public void open(Map config, SourceContext sourceContext) throws Exception { + public void open(Map config, SourceContext sourceContext) throws Exception { context = sourceContext; queue = new LinkedBlockingQueue<>(); } @@ -448,7 +448,7 @@ public static class TestSinkConnector implements Sink { SinkContext context; @Override - public void open(Map config, SinkContext sinkContext) throws Exception { + public void open(Map config, SinkContext sinkContext) throws Exception { this.context = sinkContext; } diff --git a/pulsar-functions/instance/src/test/java/org/apache/pulsar/functions/instance/ProducerBuilderFactoryTest.java b/pulsar-functions/instance/src/test/java/org/apache/pulsar/functions/instance/ProducerBuilderFactoryTest.java index a05c54709f1dd..bbdc4b8cd4366 100644 --- a/pulsar-functions/instance/src/test/java/org/apache/pulsar/functions/instance/ProducerBuilderFactoryTest.java +++ b/pulsar-functions/instance/src/test/java/org/apache/pulsar/functions/instance/ProducerBuilderFactoryTest.java @@ -52,7 +52,7 @@ public class ProducerBuilderFactoryTest { private PulsarClient pulsarClient; - private ProducerBuilder producerBuilder; + private ProducerBuilder producerBuilder; @BeforeMethod public void setup() { diff --git a/pulsar-functions/instance/src/test/java/org/apache/pulsar/functions/instance/ProducerCacheTest.java b/pulsar-functions/instance/src/test/java/org/apache/pulsar/functions/instance/ProducerCacheTest.java index 129651c880462..3994ea39a8637 100644 --- a/pulsar-functions/instance/src/test/java/org/apache/pulsar/functions/instance/ProducerCacheTest.java +++ b/pulsar-functions/instance/src/test/java/org/apache/pulsar/functions/instance/ProducerCacheTest.java @@ -33,7 +33,7 @@ public class ProducerCacheTest { @Test public void shouldTolerateAlreadyClosedExceptionInClose() { ProducerCache cache = new ProducerCache(); - Producer producer = mock(Producer.class); + Producer producer = mock(Producer.class); when(producer.flushAsync()).thenReturn(CompletableFuture.completedFuture(null)); when(producer.closeAsync()).thenReturn( CompletableFuture.failedFuture(new PulsarClientException.AlreadyClosedException("Already closed"))); @@ -45,7 +45,7 @@ public void shouldTolerateAlreadyClosedExceptionInClose() { @Test public void shouldTolerateRuntimeExceptionInClose() { ProducerCache cache = new ProducerCache(); - Producer producer = mock(Producer.class); + Producer producer = mock(Producer.class); when(producer.flushAsync()).thenReturn(CompletableFuture.completedFuture(null)); when(producer.closeAsync()).thenThrow(new RuntimeException("Some exception")); cache.getOrCreateProducer(ProducerCache.CacheArea.CONTEXT_CACHE, "topic", "key", @@ -56,7 +56,7 @@ public void shouldTolerateRuntimeExceptionInClose() { @Test public void shouldTolerateRuntimeExceptionInFlush() { ProducerCache cache = new ProducerCache(); - Producer producer = mock(Producer.class); + Producer producer = mock(Producer.class); when(producer.flushAsync()).thenThrow(new RuntimeException("Some exception")); when(producer.closeAsync()).thenReturn(CompletableFuture.completedFuture(null)); cache.getOrCreateProducer(ProducerCache.CacheArea.CONTEXT_CACHE, "topic", "key", @@ -67,7 +67,7 @@ public void shouldTolerateRuntimeExceptionInFlush() { @Test public void shouldCompleteFlushBeforeCloseAndWaitForClosing() { ProducerCache cache = new ProducerCache(); - Producer producer = mock(Producer.class); + Producer producer = mock(Producer.class); AtomicBoolean flushCompleted = new AtomicBoolean(false); when(producer.flushAsync()).thenReturn(CompletableFuture.supplyAsync(() -> { try { diff --git a/pulsar-functions/instance/src/test/java/org/apache/pulsar/functions/instance/SinkRecordTest.java b/pulsar-functions/instance/src/test/java/org/apache/pulsar/functions/instance/SinkRecordTest.java index 7ee55020a4d7a..78c449f5c1cb3 100644 --- a/pulsar-functions/instance/src/test/java/org/apache/pulsar/functions/instance/SinkRecordTest.java +++ b/pulsar-functions/instance/src/test/java/org/apache/pulsar/functions/instance/SinkRecordTest.java @@ -29,10 +29,11 @@ public class SinkRecordTest { @Test + @SuppressWarnings("rawtypes") public void testCustomAck() { PulsarRecord pulsarRecord = Mockito.mock(PulsarRecord.class); - SinkRecord sinkRecord = new SinkRecord<>(pulsarRecord, new Object()); + SinkRecord sinkRecord = new SinkRecord(pulsarRecord, new Object()); sinkRecord.cumulativeAck(); Mockito.verify(pulsarRecord, Mockito.times(1)).cumulativeAck(); diff --git a/pulsar-functions/instance/src/test/java/org/apache/pulsar/functions/instance/state/BKStateStoreImplTest.java b/pulsar-functions/instance/src/test/java/org/apache/pulsar/functions/instance/state/BKStateStoreImplTest.java index 598fb4f6e0dde..2d832fb7e2a06 100644 --- a/pulsar-functions/instance/src/test/java/org/apache/pulsar/functions/instance/state/BKStateStoreImplTest.java +++ b/pulsar-functions/instance/src/test/java/org/apache/pulsar/functions/instance/state/BKStateStoreImplTest.java @@ -118,6 +118,7 @@ public void testGetValue() throws Exception { @Test public void testGetStateValue() throws Exception { + @SuppressWarnings("rawtypes") KeyValue returnedKeyValue = mock(KeyValue.class); ByteBuf returnedValue = Unpooled.copiedBuffer("test-value", UTF_8); when(returnedKeyValue.value()).thenReturn(returnedValue); diff --git a/pulsar-functions/instance/src/test/java/org/apache/pulsar/functions/sink/PulsarSinkTest.java b/pulsar-functions/instance/src/test/java/org/apache/pulsar/functions/sink/PulsarSinkTest.java index 35a66ddd05208..3ca2a5f48627c 100644 --- a/pulsar-functions/instance/src/test/java/org/apache/pulsar/functions/sink/PulsarSinkTest.java +++ b/pulsar-functions/instance/src/test/java/org/apache/pulsar/functions/sink/PulsarSinkTest.java @@ -100,17 +100,17 @@ private static PulsarClientImpl getPulsarClient() throws PulsarClientException { PulsarClientImpl pulsarClient = mock(PulsarClientImpl.class); ConnectionPool connectionPool = mock(ConnectionPool.class); when(pulsarClient.getCnxPool()).thenReturn(connectionPool); - ConsumerBuilder consumerBuilder = mock(ConsumerBuilder.class); + ConsumerBuilder consumerBuilder = mock(ConsumerBuilder.class); doReturn(consumerBuilder).when(consumerBuilder).topics(anyList()); doReturn(consumerBuilder).when(consumerBuilder).subscriptionName(anyString()); doReturn(consumerBuilder).when(consumerBuilder).subscriptionType(any()); doReturn(consumerBuilder).when(consumerBuilder).ackTimeout(anyLong(), any()); - Consumer consumer = mock(Consumer.class); + Consumer consumer = mock(Consumer.class); doReturn(consumer).when(consumerBuilder).subscribe(); doReturn(consumerBuilder).when(pulsarClient).newConsumer(any()); doReturn(CompletableFuture.completedFuture(Optional.empty())).when(pulsarClient).getSchema(anyString()); - ProducerBuilder producerBuilder = mock(ProducerBuilder.class); + ProducerBuilder producerBuilder = mock(ProducerBuilder.class); doReturn(producerBuilder).when(producerBuilder).blockIfQueueFull(anyBoolean()); doReturn(producerBuilder).when(producerBuilder).enableBatching(anyBoolean()); doReturn(producerBuilder).when(producerBuilder).batchingMaxPublishDelay(anyLong(), any()); @@ -124,12 +124,12 @@ private static PulsarClientImpl getPulsarClient() throws PulsarClientException { doReturn(producerBuilder).when(producerBuilder).properties(any()); doReturn(producerBuilder).when(producerBuilder).sendTimeout(anyInt(), any()); - CompletableFuture completableFuture = new CompletableFuture<>(); + CompletableFuture completableFuture = new CompletableFuture<>(); completableFuture.complete(mock(MessageId.class)); - TypedMessageBuilder typedMessageBuilder = mock(TypedMessageBuilder.class); + TypedMessageBuilder typedMessageBuilder = mock(TypedMessageBuilder.class); doReturn(completableFuture).when(typedMessageBuilder).sendAsync(); - Producer producer = mock(Producer.class); + Producer producer = mock(Producer.class); doReturn(producer).when(producerBuilder).create(); doReturn(typedMessageBuilder).when(producer).newMessage(); doReturn(typedMessageBuilder).when(producer).newMessage(any(Schema.class)); @@ -190,12 +190,12 @@ public void testVoidOutputClasses() throws Exception { PulsarSinkConfig pulsarConfig = getPulsarConfigs(); // set type to void pulsarConfig.setTypeClassName(Void.class.getName()); - PulsarSink pulsarSink = - new PulsarSink(getPulsarClient(), pulsarConfig, new HashMap<>(), mock(ComponentStatsManager.class), + PulsarSink pulsarSink = + new PulsarSink<>(getPulsarClient(), pulsarConfig, new HashMap<>(), mock(ComponentStatsManager.class), Thread.currentThread().getContextClassLoader(), producerCache); try { - Schema schema = pulsarSink.initializeSchema(); + Schema schema = pulsarSink.initializeSchema(); assertNull(schema); } catch (Exception ex) { ex.printStackTrace(); @@ -210,8 +210,8 @@ public void testInconsistentOutputType() throws IOException { // set type to be inconsistent to that of SerDe pulsarConfig.setTypeClassName(Integer.class.getName()); pulsarConfig.setSerdeClassName(TestSerDe.class.getName()); - PulsarSink pulsarSink = - new PulsarSink(getPulsarClient(), pulsarConfig, new HashMap<>(), mock(ComponentStatsManager.class), + PulsarSink pulsarSink = + new PulsarSink<>(getPulsarClient(), pulsarConfig, new HashMap<>(), mock(ComponentStatsManager.class), Thread.currentThread().getContextClassLoader(), producerCache); try { pulsarSink.initializeSchema(); @@ -235,8 +235,8 @@ public void testDefaultSerDe() throws PulsarClientException { PulsarSinkConfig pulsarConfig = getPulsarConfigs(); // set type to void pulsarConfig.setTypeClassName(String.class.getName()); - PulsarSink pulsarSink = - new PulsarSink(getPulsarClient(), pulsarConfig, new HashMap<>(), mock(ComponentStatsManager.class), + PulsarSink pulsarSink = + new PulsarSink<>(getPulsarClient(), pulsarConfig, new HashMap<>(), mock(ComponentStatsManager.class), Thread.currentThread().getContextClassLoader(), producerCache); try { @@ -256,8 +256,8 @@ public void testExplicitDefaultSerDe() throws PulsarClientException { // set type to void pulsarConfig.setTypeClassName(String.class.getName()); pulsarConfig.setSerdeClassName(TopicSchema.DEFAULT_SERDE); - PulsarSink pulsarSink = - new PulsarSink(getPulsarClient(), pulsarConfig, new HashMap<>(), mock(ComponentStatsManager.class), + PulsarSink pulsarSink = + new PulsarSink<>(getPulsarClient(), pulsarConfig, new HashMap<>(), mock(ComponentStatsManager.class), Thread.currentThread().getContextClassLoader(), producerCache); try { @@ -274,8 +274,8 @@ public void testComplexOuputType() throws PulsarClientException { // set type to void pulsarConfig.setTypeClassName(ComplexUserDefinedType.class.getName()); pulsarConfig.setSerdeClassName(ComplexSerDe.class.getName()); - PulsarSink pulsarSink = - new PulsarSink(getPulsarClient(), pulsarConfig, new HashMap<>(), mock(ComponentStatsManager.class), + PulsarSink pulsarSink = + new PulsarSink<>(getPulsarClient(), pulsarConfig, new HashMap<>(), mock(ComponentStatsManager.class), Thread.currentThread().getContextClassLoader(), producerCache); try { @@ -294,7 +294,7 @@ public void testInitializeSchema() throws Exception { PulsarSinkConfig pulsarSinkConfig = getPulsarConfigs(); pulsarSinkConfig.setSerdeClassName(null); pulsarSinkConfig.setTypeClassName(GenericRecord.class.getName()); - PulsarSink sink = new PulsarSink( + PulsarSink sink = new PulsarSink<>( pulsarClient, pulsarSinkConfig, new HashMap<>(), mock(ComponentStatsManager.class), Thread.currentThread().getContextClassLoader(), producerCache); Schema schema = sink.initializeSchema(); @@ -303,7 +303,7 @@ public void testInitializeSchema() throws Exception { // generic record type (default serde and no schema type) pulsarSinkConfig = getPulsarConfigs(); pulsarSinkConfig.setTypeClassName(GenericRecord.class.getName()); - sink = new PulsarSink( + sink = new PulsarSink<>( pulsarClient, pulsarSinkConfig, new HashMap<>(), mock(ComponentStatsManager.class), Thread.currentThread().getContextClassLoader(), producerCache); schema = sink.initializeSchema(); @@ -314,7 +314,7 @@ public void testInitializeSchema() throws Exception { pulsarSinkConfig.setSerdeClassName(null); pulsarSinkConfig.setSchemaType(SchemaType.AVRO.toString()); pulsarSinkConfig.setTypeClassName(GenericRecord.class.getName()); - sink = new PulsarSink( + sink = new PulsarSink<>( pulsarClient, pulsarSinkConfig, new HashMap<>(), mock(ComponentStatsManager.class), Thread.currentThread().getContextClassLoader(), producerCache); schema = sink.initializeSchema(); @@ -325,7 +325,7 @@ public void testInitializeSchema() throws Exception { pulsarSinkConfig.setSerdeClassName(null); pulsarSinkConfig.setSchemaType(SchemaType.AUTO_CONSUME.toString()); pulsarSinkConfig.setTypeClassName(GenericRecord.class.getName()); - sink = new PulsarSink( + sink = new PulsarSink<>( pulsarClient, pulsarSinkConfig, new HashMap<>(), mock(ComponentStatsManager.class), Thread.currentThread().getContextClassLoader(), producerCache); schema = sink.initializeSchema(); @@ -335,7 +335,7 @@ public void testInitializeSchema() throws Exception { pulsarSinkConfig = getPulsarConfigs(); pulsarSinkConfig.setSchemaType(SchemaType.AUTO_CONSUME.toString()); pulsarSinkConfig.setTypeClassName(GenericRecord.class.getName()); - sink = new PulsarSink( + sink = new PulsarSink<>( pulsarClient, pulsarSinkConfig, new HashMap<>(), mock(ComponentStatsManager.class), Thread.currentThread().getContextClassLoader(), producerCache); schema = sink.initializeSchema(); @@ -343,6 +343,7 @@ public void testInitializeSchema() throws Exception { } @Test + @SuppressWarnings("rawtypes") public void testSinkAndMessageRouting() throws Exception { String[] topics = {"topic-1", "topic-2", "topic-3", null}; @@ -354,8 +355,8 @@ public void testSinkAndMessageRouting() throws Exception { /** test MANUAL **/ pulsarClient = getPulsarClient(); pulsarConfig.setProcessingGuarantees(ProcessingGuarantees.MANUAL); - PulsarSink pulsarSink = - new PulsarSink(pulsarClient, pulsarConfig, new HashMap<>(), mock(ComponentStatsManager.class), + PulsarSink pulsarSink = + new PulsarSink<>(pulsarClient, pulsarConfig, new HashMap<>(), mock(ComponentStatsManager.class), Thread.currentThread().getContextClassLoader(), producerCache); pulsarSink.open(new HashMap<>(), mock(SinkContext.class)); @@ -394,7 +395,7 @@ public Optional getDestinationTopic() { /** test At-least-once **/ pulsarClient = getPulsarClient(); pulsarConfig.setProcessingGuarantees(ProcessingGuarantees.ATLEAST_ONCE); - pulsarSink = new PulsarSink(pulsarClient, pulsarConfig, new HashMap<>(), mock(ComponentStatsManager.class), + pulsarSink = new PulsarSink<>(pulsarClient, pulsarConfig, new HashMap<>(), mock(ComponentStatsManager.class), Thread.currentThread().getContextClassLoader(), producerCache); pulsarSink.open(new HashMap<>(), mock(SinkContext.class)); @@ -428,7 +429,7 @@ public Optional getDestinationTopic() { /** test At-most-once **/ pulsarClient = getPulsarClient(); pulsarConfig.setProcessingGuarantees(ProcessingGuarantees.ATMOST_ONCE); - pulsarSink = new PulsarSink(pulsarClient, pulsarConfig, new HashMap<>(), mock(ComponentStatsManager.class), + pulsarSink = new PulsarSink<>(pulsarClient, pulsarConfig, new HashMap<>(), mock(ComponentStatsManager.class), Thread.currentThread().getContextClassLoader(), producerCache); pulsarSink.open(new HashMap<>(), mock(SinkContext.class)); @@ -468,7 +469,7 @@ public Optional getDestinationTopic() { /** test Effectively-once **/ pulsarClient = getPulsarClient(); pulsarConfig.setProcessingGuarantees(FunctionConfig.ProcessingGuarantees.EFFECTIVELY_ONCE); - pulsarSink = new PulsarSink(pulsarClient, pulsarConfig, new HashMap<>(), mock(ComponentStatsManager.class), + pulsarSink = new PulsarSink<>(pulsarClient, pulsarConfig, new HashMap<>(), mock(ComponentStatsManager.class), Thread.currentThread().getContextClassLoader(), producerCache); pulsarSink.open(new HashMap<>(), mock(SinkContext.class)); @@ -550,6 +551,7 @@ public void testWriteGenericRecordsEOS() throws Exception { testWriteGenericRecords(ProcessingGuarantees.EFFECTIVELY_ONCE); } + @SuppressWarnings("rawtypes") private void testWriteGenericRecords(ProcessingGuarantees guarantees) throws Exception { String defaultTopic = "default"; @@ -559,7 +561,7 @@ private void testWriteGenericRecords(ProcessingGuarantees guarantees) throws Exc sinkConfig.setProcessingGuarantees(guarantees); PulsarClient client = getPulsarClient(); - PulsarSink pulsarSink = new PulsarSink( + PulsarSink pulsarSink = new PulsarSink<>( client, sinkConfig, new HashMap<>(), mock(ComponentStatsManager.class), Thread.currentThread().getContextClassLoader(), producerCache); diff --git a/pulsar-functions/instance/src/test/java/org/apache/pulsar/functions/source/PulsarFunctionRecordTest.java b/pulsar-functions/instance/src/test/java/org/apache/pulsar/functions/source/PulsarFunctionRecordTest.java index 84242505ffd27..5cdc2e1bd5a05 100644 --- a/pulsar-functions/instance/src/test/java/org/apache/pulsar/functions/source/PulsarFunctionRecordTest.java +++ b/pulsar-functions/instance/src/test/java/org/apache/pulsar/functions/source/PulsarFunctionRecordTest.java @@ -30,10 +30,10 @@ public class PulsarFunctionRecordTest { @Test public void testAck() { - Record record = mock(Record.class); + Record record = mock(Record.class); Function.FunctionDetails functionDetails = Function.FunctionDetails.newBuilder().setAutoAck(true) .setProcessingGuarantees(Function.ProcessingGuarantees.ATMOST_ONCE).build(); - PulsarFunctionRecord pulsarFunctionRecord = new PulsarFunctionRecord<>(record, functionDetails); + PulsarFunctionRecord pulsarFunctionRecord = new PulsarFunctionRecord<>(record, functionDetails); pulsarFunctionRecord.ack(); verify(record, times(0)).ack(); diff --git a/pulsar-functions/instance/src/test/java/org/apache/pulsar/functions/windowing/WindowFunctionExecutorTest.java b/pulsar-functions/instance/src/test/java/org/apache/pulsar/functions/windowing/WindowFunctionExecutorTest.java index b19a6adab5187..d763db12a938d 100644 --- a/pulsar-functions/instance/src/test/java/org/apache/pulsar/functions/windowing/WindowFunctionExecutorTest.java +++ b/pulsar-functions/instance/src/test/java/org/apache/pulsar/functions/windowing/WindowFunctionExecutorTest.java @@ -136,6 +136,7 @@ public void testWindowFunctionWithAtmostOnce() throws Exception { windowConfig.setProcessingGuarantees(WindowConfig.ProcessingGuarantees.ATMOST_ONCE); doReturn(Optional.of(new Gson().fromJson(new Gson().toJson(windowConfig), Map.class))).when(context) .getUserConfigValue(WindowConfig.WINDOW_CONFIG_KEY); + @SuppressWarnings("rawtypes") Record record = mock(Record.class); when(context.getCurrentRecord()).thenReturn(record); doReturn(Optional.of("test-topic")).when(record).getTopicName(); @@ -150,6 +151,7 @@ public void testWindowFunctionWithAtleastOnce() throws Exception { WindowConfig config = new WindowConfig(); config.setProcessingGuarantees(WindowConfig.ProcessingGuarantees.ATLEAST_ONCE); + @SuppressWarnings("rawtypes") WindowFunctionExecutor windowFunctionExecutor = spy(WindowFunctionExecutor.class); windowFunctionExecutor.windowConfig = config; doNothing().when(windowFunctionExecutor).initialize(any()); @@ -253,6 +255,7 @@ public void testExecuteWithLateTupleStream() throws Exception { windowConfig.setLateDataTopic("$late"); doReturn(Optional.of(new Gson().fromJson(new Gson().toJson(windowConfig), Map.class))) .when(context).getUserConfigValue(WindowConfig.WINDOW_CONFIG_KEY); + @SuppressWarnings("rawtypes") TypedMessageBuilder typedMessageBuilder = mock(TypedMessageBuilder.class); when(typedMessageBuilder.value(any())).thenReturn(typedMessageBuilder); when(typedMessageBuilder.sendAsync()).thenReturn(CompletableFuture.anyOf()); diff --git a/pulsar-functions/instance/src/test/java/org/apache/pulsar/functions/windowing/WindowManagerTest.java b/pulsar-functions/instance/src/test/java/org/apache/pulsar/functions/windowing/WindowManagerTest.java index 442be8130c1a2..39e6c63f92530 100644 --- a/pulsar-functions/instance/src/test/java/org/apache/pulsar/functions/windowing/WindowManagerTest.java +++ b/pulsar-functions/instance/src/test/java/org/apache/pulsar/functions/windowing/WindowManagerTest.java @@ -171,6 +171,7 @@ public void testExpireThreshold() throws Exception { assertEquals(seq(1, threshold - windowLength), listener.onExpiryEvents); } + @SuppressWarnings("rawtypes") private void testEvictBeforeWatermarkForWatermarkEvictionPolicy(EvictionPolicy watermarkEvictionPolicy, int windowLength) throws @@ -386,43 +387,43 @@ public void testEventTimeBasedWindow() throws Exception { windowManager.add(new WaterMarkEvent(631)); assertEquals(3, listener.allOnActivationEvents.size()); - assertEquals(Arrays.asList(new Event[]{ + assertEquals(Arrays.asList(new Event[]{ new EventImpl<>(1, 603, null), new EventImpl<>(2, 605, null), new EventImpl<>(3, 607, null) }), listener.allOnActivationEvents.get(0)); - assertEquals(Arrays.asList(new Event[]{ + assertEquals(Arrays.asList(new Event[]{ new EventImpl<>(1, 603, null), new EventImpl<>(2, 605, null), new EventImpl<>(3, 607, null), new EventImpl<>(4, 618, null) }), listener.allOnActivationEvents.get(1)); - assertEquals(Arrays.asList(new Event[]{ + assertEquals(Arrays.asList(new Event[]{ new EventImpl<>(4, 618, null), new EventImpl<>(5, 626, null) }), listener.allOnActivationEvents.get(2)); assertEquals(Collections.emptyList(), listener.allOnActivationExpiredEvents.get(0)); assertEquals(Collections.emptyList(), listener.allOnActivationExpiredEvents.get(1)); - assertEquals(Arrays.asList(new Event[]{ + assertEquals(Arrays.asList(new Event[]{ new EventImpl<>(1, 603, null), new EventImpl<>(2, 605, null), new EventImpl<>(3, 607, null) }), listener.allOnActivationExpiredEvents.get(2)); - assertEquals(Arrays.asList(new Event[]{ + assertEquals(Arrays.asList(new Event[]{ new EventImpl<>(1, 603, null), new EventImpl<>(2, 605, null), new EventImpl<>(3, 607, null) }), listener.allOnActivationNewEvents.get(0)); - assertEquals(Arrays.asList(new Event[]{ + assertEquals(Arrays.asList(new Event[]{ new EventImpl<>(4, 618, null) }), listener.allOnActivationNewEvents.get(1)); - assertEquals(Arrays.asList(new Event[]{ + assertEquals(Arrays.asList(new Event[]{ new EventImpl<>(5, 626, null) }), listener.allOnActivationNewEvents.get(2)); - assertEquals(Arrays.asList(new Event[]{ + assertEquals(Arrays.asList(new Event[]{ new EventImpl<>(1, 603, null), new EventImpl<>(2, 605, null), new EventImpl<>(3, 607, null) @@ -438,44 +439,44 @@ public void testEventTimeBasedWindow() throws Exception { windowManager.add(new WaterMarkEvent(834)); assertEquals(3, listener.allOnActivationEvents.size()); - assertEquals(Arrays.asList(new Event[]{ + assertEquals(Arrays.asList(new Event[]{ new EventImpl<>(5, 626, null), new EventImpl<>(6, 636, null) }), listener.allOnActivationEvents.get(0)); - assertEquals(Arrays.asList(new Event[]{ + assertEquals(Arrays.asList(new Event[]{ new EventImpl<>(6, 636, null) }), listener.allOnActivationEvents.get(1)); - assertEquals(Arrays.asList(new Event[]{ + assertEquals(Arrays.asList(new Event[]{ new EventImpl<>(7, 825, null), new EventImpl<>(8, 826, null), new EventImpl<>(9, 827, null) }), listener.allOnActivationEvents.get(2)); - assertEquals(Arrays.asList(new Event[]{ + assertEquals(Arrays.asList(new Event[]{ new EventImpl<>(4, 618, null) }), listener.allOnActivationExpiredEvents.get(0)); - assertEquals(Arrays.asList(new Event[]{ + assertEquals(Arrays.asList(new Event[]{ new EventImpl<>(5, 626, null) }), listener.allOnActivationExpiredEvents.get(1)); assertEquals(Collections.emptyList(), listener.allOnActivationExpiredEvents.get(2)); - assertEquals(Arrays.asList(new Event[]{ + assertEquals(Arrays.asList(new Event[]{ new EventImpl<>(6, 636, null) }), listener.allOnActivationNewEvents.get(0)); assertEquals(Collections.emptyList(), listener.allOnActivationNewEvents.get(1)); - assertEquals(Arrays.asList(new Event[]{ + assertEquals(Arrays.asList(new Event[]{ new EventImpl<>(7, 825, null), new EventImpl<>(8, 826, null), new EventImpl<>(9, 827, null) }), listener.allOnActivationNewEvents.get(2)); - assertEquals(Arrays.asList(new Event[]{ + assertEquals(Arrays.asList(new Event[]{ new EventImpl<>(4, 618, null) }), listener.allOnExpiryEvents.get(0)); - assertEquals(Arrays.asList(new Event[]{ + assertEquals(Arrays.asList(new Event[]{ new EventImpl<>(5, 626, null) }), listener.allOnExpiryEvents.get(1)); - assertEquals(Arrays.asList(new Event[]{ + assertEquals(Arrays.asList(new Event[]{ new EventImpl<>(6, 636, null) }), listener.allOnExpiryEvents.get(2)); } @@ -499,17 +500,17 @@ public void testCountBasedWindowWithEventTs() throws Exception { windowManager.add(new WaterMarkEvent(631)); assertEquals(3, listener.allOnActivationEvents.size()); - assertEquals(Arrays.asList(new Event[]{ + assertEquals(Arrays.asList(new Event[]{ new EventImpl<>(1, 603, null), new EventImpl<>(2, 605, null), new EventImpl<>(3, 607, null) }), listener.allOnActivationEvents.get(0)); - assertEquals(Arrays.asList(new Event[]{ + assertEquals(Arrays.asList(new Event[]{ new EventImpl<>(2, 605, null), new EventImpl<>(3, 607, null), new EventImpl<>(4, 618, null) }), listener.allOnActivationEvents.get(1)); - assertEquals(Arrays.asList(new Event[]{ + assertEquals(Arrays.asList(new Event[]{ new EventImpl<>(3, 607, null), new EventImpl<>(4, 618, null), new EventImpl<>(5, 626, null) @@ -525,22 +526,22 @@ public void testCountBasedWindowWithEventTs() throws Exception { windowManager.add(new WaterMarkEvent(674)); assertEquals(4, listener.allOnActivationEvents.size()); // same set of events part of three windows - assertEquals(Arrays.asList(new Event[]{ + assertEquals(Arrays.asList(new Event[]{ new EventImpl<>(4, 618, null), new EventImpl<>(5, 626, null), new EventImpl<>(6, 636, null) }), listener.allOnActivationEvents.get(0)); - assertEquals(Arrays.asList(new Event[]{ + assertEquals(Arrays.asList(new Event[]{ new EventImpl<>(4, 618, null), new EventImpl<>(5, 626, null), new EventImpl<>(6, 636, null) }), listener.allOnActivationEvents.get(1)); - assertEquals(Arrays.asList(new Event[]{ + assertEquals(Arrays.asList(new Event[]{ new EventImpl<>(4, 618, null), new EventImpl<>(5, 626, null), new EventImpl<>(6, 636, null) }), listener.allOnActivationEvents.get(2)); - assertEquals(Arrays.asList(new Event[]{ + assertEquals(Arrays.asList(new Event[]{ new EventImpl<>(7, 665, null), new EventImpl<>(8, 666, null), new EventImpl<>(9, 667, null) @@ -568,12 +569,12 @@ public void testCountBasedTriggerWithEventTs() throws Exception { windowManager.add(new WaterMarkEvent(631)); assertEquals(2, listener.allOnActivationEvents.size()); - assertEquals(Arrays.asList(new Event[]{ + assertEquals(Arrays.asList(new Event[]{ new EventImpl<>(1, 603, null), new EventImpl<>(2, 605, null), new EventImpl<>(3, 607, null) }), listener.allOnActivationEvents.get(0)); - assertEquals(Arrays.asList(new Event[]{ + assertEquals(Arrays.asList(new Event[]{ new EventImpl<>(3, 607, null), new EventImpl<>(4, 618, null), new EventImpl<>(5, 625, null), @@ -592,10 +593,10 @@ public void testCountBasedTriggerWithEventTs() throws Exception { windowManager.add(new WaterMarkEvent(674)); assertEquals(2, listener.allOnActivationEvents.size()); // same set of events part of three windows - assertEquals(Arrays.asList(new Event[]{ + assertEquals(Arrays.asList(new Event[]{ new EventImpl<>(9, 665, null) }), listener.allOnActivationEvents.get(0)); - assertEquals(Arrays.asList(new Event[]{ + assertEquals(Arrays.asList(new Event[]{ new EventImpl<>(9, 665, null), new EventImpl<>(10, 666, null), new EventImpl<>(11, 667, null), @@ -625,23 +626,23 @@ public void testCountBasedTumblingWithSameEventTs() throws Exception { windowManager.add(new WaterMarkEvent(20)); assertEquals(5, listener.allOnActivationEvents.size()); - assertEquals(Arrays.asList(new Event[]{ + assertEquals(Arrays.asList(new Event[]{ new EventImpl<>(1, 10, null), new EventImpl<>(2, 10, null) }), listener.allOnActivationEvents.get(0)); - assertEquals(Arrays.asList(new Event[]{ + assertEquals(Arrays.asList(new Event[]{ new EventImpl<>(3, 11, null), new EventImpl<>(4, 12, null) }), listener.allOnActivationEvents.get(1)); - assertEquals(Arrays.asList(new Event[]{ + assertEquals(Arrays.asList(new Event[]{ new EventImpl<>(5, 12, null), new EventImpl<>(6, 12, null) }), listener.allOnActivationEvents.get(2)); - assertEquals(Arrays.asList(new Event[]{ + assertEquals(Arrays.asList(new Event[]{ new EventImpl<>(7, 12, null), new EventImpl<>(8, 13, null) }), listener.allOnActivationEvents.get(3)); - assertEquals(Arrays.asList(new Event[]{ + assertEquals(Arrays.asList(new Event[]{ new EventImpl<>(9, 14, null), new EventImpl<>(10, 15, null) }), listener.allOnActivationEvents.get(4)); @@ -669,31 +670,31 @@ public void testCountBasedSlidingWithSameEventTs() throws Exception { windowManager.add(new WaterMarkEvent(20)); assertEquals(5, listener.allOnActivationEvents.size()); - assertEquals(Arrays.asList(new Event[]{ + assertEquals(Arrays.asList(new Event[]{ new EventImpl<>(1, 10, null), new EventImpl<>(2, 10, null) }), listener.allOnActivationEvents.get(0)); - assertEquals(Arrays.asList(new Event[]{ + assertEquals(Arrays.asList(new Event[]{ new EventImpl<>(1, 10, null), new EventImpl<>(2, 10, null), new EventImpl<>(3, 11, null), new EventImpl<>(4, 12, null) }), listener.allOnActivationEvents.get(1)); - assertEquals(Arrays.asList(new Event[]{ + assertEquals(Arrays.asList(new Event[]{ new EventImpl<>(2, 10, null), new EventImpl<>(3, 11, null), new EventImpl<>(4, 12, null), new EventImpl<>(5, 12, null), new EventImpl<>(6, 12, null) }), listener.allOnActivationEvents.get(2)); - assertEquals(Arrays.asList(new Event[]{ + assertEquals(Arrays.asList(new Event[]{ new EventImpl<>(4, 12, null), new EventImpl<>(5, 12, null), new EventImpl<>(6, 12, null), new EventImpl<>(7, 12, null), new EventImpl<>(8, 13, null) }), listener.allOnActivationEvents.get(3)); - assertEquals(Arrays.asList(new Event[]{ + assertEquals(Arrays.asList(new Event[]{ new EventImpl<>(6, 12, null), new EventImpl<>(7, 12, null), new EventImpl<>(8, 13, null), @@ -722,19 +723,19 @@ public void testEventTimeLag() throws Exception { // send a watermark event, which should trigger three windows. windowManager.add(new WaterMarkEvent(631)); assertEquals(3, listener.allOnActivationEvents.size()); - assertEquals(Arrays.asList(new Event[]{ + assertEquals(Arrays.asList(new Event[]{ new EventImpl<>(1, 603, null), new EventImpl<>(2, 605, null), new EventImpl<>(3, 607, null), }), listener.allOnActivationEvents.get(0)); - assertEquals(Arrays.asList(new Event[]{ + assertEquals(Arrays.asList(new Event[]{ new EventImpl<>(1, 603, null), new EventImpl<>(2, 605, null), new EventImpl<>(3, 607, null), new EventImpl<>(4, 618, null), }), listener.allOnActivationEvents.get(1)); // out of order events should be processed upto the lag - assertEquals(Arrays.asList(new Event[]{ + assertEquals(Arrays.asList(new Event[]{ new EventImpl<>(4, 618, null), new EventImpl<>(5, 626, null), new EventImpl<>(7, 629, null) @@ -774,12 +775,12 @@ public Action evict(Event event) { windowManager.add(new WaterMarkEvent(631)); assertEquals(3, listener.allOnActivationEvents.size()); - assertEquals(Arrays.asList(new Event[]{ + assertEquals(Arrays.asList(new Event[]{ new EventImpl<>(1, 603, null), new EventImpl<>(2, 605, null), new EventImpl<>(3, 607, null), }), listener.allOnActivationEvents.get(0)); - assertEquals(Arrays.asList(new Event[]{ + assertEquals(Arrays.asList(new Event[]{ new EventImpl<>(1, 603, null), new EventImpl<>(2, 605, null), new EventImpl<>(3, 607, null), @@ -787,7 +788,7 @@ public Action evict(Event event) { }), listener.allOnActivationEvents.get(1)); // out of order events should be processed upto the lag - assertEquals(Arrays.asList(new Event[]{ + assertEquals(Arrays.asList(new Event[]{ new EventImpl<>(4, 618, null), new EventImpl<>(5, 626, null), new EventImpl<>(6, 629, null) @@ -795,7 +796,7 @@ public Action evict(Event event) { // events 8, 9, 10 should not be scanned at all since TimeEvictionPolicy lag 5s should break // the WindowManager scan loop early. - assertEquals(new HashSet<>(Arrays.asList(new Event[]{ + assertEquals(new HashSet<>(Arrays.asList(new Event[]{ new EventImpl<>(1, 603, null), new EventImpl<>(2, 605, null), new EventImpl<>(3, 607, null), diff --git a/pulsar-functions/runtime/src/test/java/org/apache/pulsar/functions/runtime/kubernetes/KubernetesRuntimeTest.java b/pulsar-functions/runtime/src/test/java/org/apache/pulsar/functions/runtime/kubernetes/KubernetesRuntimeTest.java index 2be701c832a8a..5bbdba9c71335 100644 --- a/pulsar-functions/runtime/src/test/java/org/apache/pulsar/functions/runtime/kubernetes/KubernetesRuntimeTest.java +++ b/pulsar-functions/runtime/src/test/java/org/apache/pulsar/functions/runtime/kubernetes/KubernetesRuntimeTest.java @@ -1013,7 +1013,7 @@ private void verifyGolangInstance(InstanceConfig config) throws Exception { assertEquals(args.size(), totalArgs, "Actual args : " + StringUtils.join(args, " ")); - HashMap goInstanceConfig = new ObjectMapper().readValue(args.get(7).replaceAll("^\'|\'$", + HashMap goInstanceConfig = new ObjectMapper().readValue(args.get(7).replaceAll("^\'|\'$", ""), HashMap.class); assertEquals(args.get(0), "chmod"); diff --git a/pulsar-functions/worker/src/test/java/org/apache/pulsar/functions/worker/FunctionMetaDataManagerTest.java b/pulsar-functions/worker/src/test/java/org/apache/pulsar/functions/worker/FunctionMetaDataManagerTest.java index 841af27e9b47a..548462bf61a59 100644 --- a/pulsar-functions/worker/src/test/java/org/apache/pulsar/functions/worker/FunctionMetaDataManagerTest.java +++ b/pulsar-functions/worker/src/test/java/org/apache/pulsar/functions/worker/FunctionMetaDataManagerTest.java @@ -64,7 +64,9 @@ private static PulsarClient mockPulsarClient() throws PulsarClientException { when(builder.sendTimeout(anyInt(), any(TimeUnit.class))).thenReturn(builder); when(builder.accessMode(any())).thenReturn(builder); + @SuppressWarnings("rawtypes") Producer producer = mock(Producer.class); + @SuppressWarnings("rawtypes") TypedMessageBuilder messageBuilder = mock(TypedMessageBuilder.class); when(messageBuilder.key(anyString())).thenReturn(messageBuilder); doAnswer(invocation -> { @@ -304,6 +306,7 @@ public void testProcessRequest() throws PulsarClientException, IOException { Request.ServiceRequest serviceRequest = Request.ServiceRequest.newBuilder().setServiceRequestType( Request.ServiceRequest.ServiceRequestType.UPDATE).build(); + @SuppressWarnings("rawtypes") Message msg = mock(Message.class); doReturn(serviceRequest.toByteArray()).when(msg).getData(); functionMetaDataManager.processMetaDataTopicMessage(msg); diff --git a/pulsar-functions/worker/src/test/java/org/apache/pulsar/functions/worker/FunctionWorkerStarterTest.java b/pulsar-functions/worker/src/test/java/org/apache/pulsar/functions/worker/FunctionWorkerStarterTest.java index 6fa0bec1b362d..54d0d289816d1 100644 --- a/pulsar-functions/worker/src/test/java/org/apache/pulsar/functions/worker/FunctionWorkerStarterTest.java +++ b/pulsar-functions/worker/src/test/java/org/apache/pulsar/functions/worker/FunctionWorkerStarterTest.java @@ -34,7 +34,7 @@ public void testMainGenerateDocs() throws Exception { ByteArrayOutputStream baoStream = new ByteArrayOutputStream(); System.setOut(new PrintStream(baoStream)); - Class argumentsClass = + Class argumentsClass = Class.forName("org.apache.pulsar.functions.worker.FunctionWorkerStarter$WorkerArguments"); FunctionWorkerStarter.main(new String[]{"-g"}); diff --git a/pulsar-functions/worker/src/test/java/org/apache/pulsar/functions/worker/LeaderServiceTest.java b/pulsar-functions/worker/src/test/java/org/apache/pulsar/functions/worker/LeaderServiceTest.java index 5c10a59bd1388..48e4fc9fe90a1 100644 --- a/pulsar-functions/worker/src/test/java/org/apache/pulsar/functions/worker/LeaderServiceTest.java +++ b/pulsar-functions/worker/src/test/java/org/apache/pulsar/functions/worker/LeaderServiceTest.java @@ -52,14 +52,15 @@ public class LeaderServiceTest { AtomicReference listenerHolder; private LeaderService leaderService; private PulsarClientImpl mockClient; + @SuppressWarnings("rawtypes") private ConsumerImpl mockConsumer; private FunctionAssignmentTailer functionAssignmentTailer; private SchedulerManager schedulerManager; private FunctionRuntimeManager functionRuntimeManager; private FunctionMetaDataManager functionMetadataManager; - private CompletableFuture metadataManagerInitFuture; - private CompletableFuture runtimeManagerInitFuture; - private CompletableFuture readToTheEndAndExitFuture; + private CompletableFuture metadataManagerInitFuture; + private CompletableFuture runtimeManagerInitFuture; + private CompletableFuture readToTheEndAndExitFuture; private MembershipManager membershipManager; public LeaderServiceTest() { diff --git a/pulsar-functions/worker/src/test/java/org/apache/pulsar/functions/worker/SchedulerManagerTest.java b/pulsar-functions/worker/src/test/java/org/apache/pulsar/functions/worker/SchedulerManagerTest.java index 9e7b8d4fa6b1b..adc555e16dd02 100644 --- a/pulsar-functions/worker/src/test/java/org/apache/pulsar/functions/worker/SchedulerManagerTest.java +++ b/pulsar-functions/worker/src/test/java/org/apache/pulsar/functions/worker/SchedulerManagerTest.java @@ -79,6 +79,7 @@ public class SchedulerManagerTest { private FunctionRuntimeManager functionRuntimeManager; private MembershipManager membershipManager; private CompletableFuture completableFuture; + @SuppressWarnings("rawtypes") private Producer producer; private TypedMessageBuilder message; private ScheduledExecutorService executor; diff --git a/pulsar-functions/worker/src/test/java/org/apache/pulsar/functions/worker/WorkerUtilsTest.java b/pulsar-functions/worker/src/test/java/org/apache/pulsar/functions/worker/WorkerUtilsTest.java index 0f5fca4a8a5a3..bfbd2db4ad664 100644 --- a/pulsar-functions/worker/src/test/java/org/apache/pulsar/functions/worker/WorkerUtilsTest.java +++ b/pulsar-functions/worker/src/test/java/org/apache/pulsar/functions/worker/WorkerUtilsTest.java @@ -79,6 +79,7 @@ public void testCreateExclusiveProducerWithRetry() { verify(builder, times(1)).producerName(eq("test-producer")); verify(builder, times(1)).accessMode(eq(ProducerAccessMode.Exclusive)); + @SuppressWarnings("rawtypes") CompletableFuture completableFuture = new CompletableFuture(); completableFuture.completeExceptionally(new PulsarClientException.ProducerFencedException("test")); when(builder.createAsync()).thenReturn(completableFuture); diff --git a/pulsar-functions/worker/src/test/java/org/apache/pulsar/functions/worker/rest/api/v3/AbstractFunctionsResourceTest.java b/pulsar-functions/worker/src/test/java/org/apache/pulsar/functions/worker/rest/api/v3/AbstractFunctionsResourceTest.java index 84edb05372c77..04b4e1298b98b 100644 --- a/pulsar-functions/worker/src/test/java/org/apache/pulsar/functions/worker/rest/api/v3/AbstractFunctionsResourceTest.java +++ b/pulsar-functions/worker/src/test/java/org/apache/pulsar/functions/worker/rest/api/v3/AbstractFunctionsResourceTest.java @@ -92,7 +92,7 @@ public abstract class AbstractFunctionsResourceTest { private static final String SYSTEM_PROPERTY_NAME_INVALID_NAR_FILE_PATH = "pulsar-io-invalid.nar.path"; private static final String SYSTEM_PROPERTY_NAME_FUNCTIONS_API_EXAMPLES_NAR_FILE_PATH = "pulsar-functions-api-examples.nar.path"; - protected static Map mockStaticContexts = new HashMap<>(); + protected static Map> mockStaticContexts = new HashMap<>(); static { TOPICS_TO_SER_DE_CLASS_NAME.put("test_src", DEFAULT_SERDE); @@ -234,8 +234,9 @@ protected void mockStatic(Class classStatic, Consumer> co mockStatic(classStatic, withSettings().defaultAnswer(Mockito.CALLS_REAL_METHODS), consumer); } + @SuppressWarnings({"unchecked", "rawtypes"}) private void mockStatic(Class classStatic, MockSettings mockSettings, Consumer> consumer) { - final MockedStatic mockedStatic = mockStaticContexts.computeIfAbsent(classStatic.getName(), + final MockedStatic mockedStatic = (MockedStatic) mockStaticContexts.computeIfAbsent(classStatic.getName(), name -> Mockito.mockStatic(classStatic, mockSettings)); consumer.accept(mockedStatic); } diff --git a/pulsar-metadata/src/test/java/org/apache/bookkeeper/replication/BookKeeperClusterTestCase.java b/pulsar-metadata/src/test/java/org/apache/bookkeeper/replication/BookKeeperClusterTestCase.java index 9724d2d6ff65d..701ef45bf1877 100644 --- a/pulsar-metadata/src/test/java/org/apache/bookkeeper/replication/BookKeeperClusterTestCase.java +++ b/pulsar-metadata/src/test/java/org/apache/bookkeeper/replication/BookKeeperClusterTestCase.java @@ -769,7 +769,7 @@ protected ServerTester startBookie(ServerConfiguration conf, final Bookie b) return tester; } - public void setMetastoreImplClass(AbstractConfiguration conf) { + public void setMetastoreImplClass(AbstractConfiguration conf) { conf.setMetastoreImplClass(InMemoryMetaStore.class.getName()); } diff --git a/pulsar-metadata/src/test/java/org/apache/pulsar/metadata/DualMetadataCacheTest.java b/pulsar-metadata/src/test/java/org/apache/pulsar/metadata/DualMetadataCacheTest.java index 88890466b7844..442e953a646f1 100644 --- a/pulsar-metadata/src/test/java/org/apache/pulsar/metadata/DualMetadataCacheTest.java +++ b/pulsar-metadata/src/test/java/org/apache/pulsar/metadata/DualMetadataCacheTest.java @@ -514,7 +514,7 @@ public void testCacheWithCustomConfig() throws Exception { MetadataStoreConfig.builder().build()); // Create cache with custom config - MetadataCacheConfig cacheConfig = MetadataCacheConfig.builder() + MetadataCacheConfig cacheConfig = MetadataCacheConfig.builder() .refreshAfterWriteMillis(1000) .build(); diff --git a/pulsar-metadata/src/test/java/org/apache/pulsar/metadata/MetadataCacheTest.java b/pulsar-metadata/src/test/java/org/apache/pulsar/metadata/MetadataCacheTest.java index 69e2377536984..30c94009df79d 100644 --- a/pulsar-metadata/src/test/java/org/apache/pulsar/metadata/MetadataCacheTest.java +++ b/pulsar-metadata/src/test/java/org/apache/pulsar/metadata/MetadataCacheTest.java @@ -531,7 +531,7 @@ public void readModifyUpdateOrCreateRetryTimeout(String provider, Supplier cacheRef = cache; - if (cache instanceof DualMetadataCache dc) { + if (cache instanceof DualMetadataCache dc) { cacheRef = (MetadataCache) dc.getMetadataCache().get(); } diff --git a/pulsar-metadata/src/test/java/org/apache/pulsar/metadata/TestZKServer.java b/pulsar-metadata/src/test/java/org/apache/pulsar/metadata/TestZKServer.java index f604dd69b0766..02052a5a81735 100644 --- a/pulsar-metadata/src/test/java/org/apache/pulsar/metadata/TestZKServer.java +++ b/pulsar-metadata/src/test/java/org/apache/pulsar/metadata/TestZKServer.java @@ -103,7 +103,7 @@ private static ZooKeeperServer getZooKeeperServer(ZooKeeperServerMain zooKeeperS } @SneakyThrows - private static T readField(Class clazz, String field, Object object) { + private static T readField(Class clazz, String field, Object object) { Field declaredField = clazz.getDeclaredField(field); boolean accessible = declaredField.isAccessible(); if (!accessible) { diff --git a/pulsar-transaction/coordinator/src/test/java/org/apache/pulsar/transaction/coordinator/impl/TxnLogBufferedWriterTest.java b/pulsar-transaction/coordinator/src/test/java/org/apache/pulsar/transaction/coordinator/impl/TxnLogBufferedWriterTest.java index fdab24dabb41a..3ec03dc9fd240 100644 --- a/pulsar-transaction/coordinator/src/test/java/org/apache/pulsar/transaction/coordinator/impl/TxnLogBufferedWriterTest.java +++ b/pulsar-transaction/coordinator/src/test/java/org/apache/pulsar/transaction/coordinator/impl/TxnLogBufferedWriterTest.java @@ -197,7 +197,7 @@ public void testMainProcess(int batchedWriteMaxRecords, int batchedWriteMaxSize, * 2. Store the param-context and param-position of callback function for verify. */ // Create TxLogBufferedWriter. - TxnLogBufferedWriter txnLogBufferedWriter = new TxnLogBufferedWriter( + TxnLogBufferedWriter txnLogBufferedWriter = new TxnLogBufferedWriter<>( managedLedger, ((ManagedLedgerImpl) managedLedger).getExecutor(), transactionTimer, dataSerializer, batchedWriteMaxRecords, batchedWriteMaxSize, batchedWriteMaxDelayInMillis, batchEnabled, DISABLED_BUFFERED_WRITER_METRICS); @@ -396,7 +396,7 @@ public void testFlushThresholds() throws Exception{ SumStrDataSerializer dataSerializer = new SumStrDataSerializer(); // Cache the data flush to Bookie for Asserts. List dataArrayFlushedToBookie = Collections.synchronizedList(new ArrayList<>()); - Mockito.doAnswer(new Answer() { + Mockito.doAnswer(new Answer() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { ByteBuf byteBuf = (ByteBuf) invocation.getArguments()[0]; @@ -410,7 +410,7 @@ public Object answer(InvocationOnMock invocation) throws Throwable { } }).when(managedLedger).asyncAddEntry(Mockito.any(ByteBuf.class), Mockito.any(), Mockito.any()); // Test threshold: writeMaxDelayInMillis (use timer). - TxnLogBufferedWriter txnLogBufferedWriter1 = new TxnLogBufferedWriter<>(managedLedger, topicExecutor, + TxnLogBufferedWriter txnLogBufferedWriter1 = new TxnLogBufferedWriter<>(managedLedger, topicExecutor, transactionTimer, dataSerializer, 32, 1024 * 4, 100, true, DISABLED_BUFFERED_WRITER_METRICS); TxnLogBufferedWriter.AddDataCallback callback = Mockito.mock(TxnLogBufferedWriter.AddDataCallback.class); @@ -423,7 +423,7 @@ public Object answer(InvocationOnMock invocation) throws Throwable { txnLogBufferedWriter1.close().get(); // Test threshold: batchedWriteMaxRecords. - TxnLogBufferedWriter txnLogBufferedWriter2 = new TxnLogBufferedWriter<>(managedLedger, topicExecutor, + TxnLogBufferedWriter txnLogBufferedWriter2 = new TxnLogBufferedWriter<>(managedLedger, topicExecutor, transactionTimer, dataSerializer, 32, 1024 * 4, 10000, true, DISABLED_BUFFERED_WRITER_METRICS); for (int i = 0; i < 32; i++){ @@ -434,7 +434,7 @@ public Object answer(InvocationOnMock invocation) throws Throwable { txnLogBufferedWriter2.close(); // Test threshold: batchedWriteMaxSize. - TxnLogBufferedWriter txnLogBufferedWriter3 = new TxnLogBufferedWriter<>(managedLedger, topicExecutor, + TxnLogBufferedWriter txnLogBufferedWriter3 = new TxnLogBufferedWriter<>(managedLedger, topicExecutor, transactionTimer, dataSerializer, 1024, 64 * 4, 10000, true, DISABLED_BUFFERED_WRITER_METRICS); for (int i = 0; i < 64; i++){ @@ -471,7 +471,7 @@ public void testPendingScheduleTriggerTaskCount() throws Exception { // Mock managed ledger and write counter. MockedManagedLedger mockedManagedLedger = mockManagedLedgerWithWriteCounter(mlName); // Start tests. - TxnLogBufferedWriter txnLogBufferedWriter = new TxnLogBufferedWriter<>(mockedManagedLedger.managedLedger, + TxnLogBufferedWriter txnLogBufferedWriter = new TxnLogBufferedWriter<>(mockedManagedLedger.managedLedger, threadPoolExecutor, transactionTimer, dataSerializer, 2, 1024 * 4, 1, true, DISABLED_BUFFERED_WRITER_METRICS); TxnLogBufferedWriter.AddDataCallback callback = Mockito.mock(TxnLogBufferedWriter.AddDataCallback.class); @@ -908,6 +908,7 @@ public void testMetricsStatsThatTriggeredByLargeSingleData() throws Exception { @Test public void testFailWhenAddData() throws Exception { int batchedWriteMaxSize = 1024; + @SuppressWarnings("rawtypes") TxnLogBufferedWriter.DataSerializer dataSerializer = new WrongDataSerializer(batchedWriteMaxSize, true, true, true); int writeCount = 100; @@ -1026,7 +1027,7 @@ private MockedManagedLedger mockManagedLedgerWithWriteCounter(String mlName){ AtomicInteger writeCounter = new AtomicInteger(); ManagedLedger managedLedger = Mockito.mock(ManagedLedger.class); Mockito.when(managedLedger.getName()).thenReturn(mlName); - Mockito.doAnswer(new Answer() { + Mockito.doAnswer(new Answer() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { writeCounter.incrementAndGet(); From 53970a3d15e40b8d42b27ae28f1c3c0a2cc45b1e Mon Sep 17 00:00:00 2001 From: Matteo Merli Date: Sat, 28 Mar 2026 21:23:49 -0700 Subject: [PATCH 2/4] [improve][test] Fix checkstyle line-length violations from rawtypes fixes --- .../pulsar/client/impl/TypedMessageBuilderImplTest.java | 3 ++- .../common/semaphore/AsyncDualMemoryLimiterUtilTest.java | 7 ++++--- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/pulsar-client/src/test/java/org/apache/pulsar/client/impl/TypedMessageBuilderImplTest.java b/pulsar-client/src/test/java/org/apache/pulsar/client/impl/TypedMessageBuilderImplTest.java index 3d0cae19196c2..4b61c32fe4939 100644 --- a/pulsar-client/src/test/java/org/apache/pulsar/client/impl/TypedMessageBuilderImplTest.java +++ b/pulsar-client/src/test/java/org/apache/pulsar/client/impl/TypedMessageBuilderImplTest.java @@ -138,7 +138,8 @@ public void testSeparatedValue() throws Exception { KeyValue keyValue = new KeyValue<>(foo, bar); // Check kv.encoding.type SEPARATED - TypedMessageBuilderImpl typedMessageBuilder = (TypedMessageBuilderImpl) typedMessageBuilderImpl.value(keyValue); + TypedMessageBuilderImpl typedMessageBuilder = + (TypedMessageBuilderImpl) typedMessageBuilderImpl.value(keyValue); Method method = TypedMessageBuilderImpl.class.getDeclaredMethod("beforeSend"); method.setAccessible(true); method.invoke(typedMessageBuilder); diff --git a/pulsar-common/src/test/java/org/apache/pulsar/common/semaphore/AsyncDualMemoryLimiterUtilTest.java b/pulsar-common/src/test/java/org/apache/pulsar/common/semaphore/AsyncDualMemoryLimiterUtilTest.java index 9f9758f5cd750..b8756c042151b 100644 --- a/pulsar-common/src/test/java/org/apache/pulsar/common/semaphore/AsyncDualMemoryLimiterUtilTest.java +++ b/pulsar-common/src/test/java/org/apache/pulsar/common/semaphore/AsyncDualMemoryLimiterUtilTest.java @@ -33,6 +33,7 @@ import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelHandlerContext; +import io.netty.util.concurrent.GenericFutureListener; import java.time.Duration; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; @@ -246,7 +247,7 @@ public void testAcquireDirectMemoryPermitsAndWriteAndFlushSuccess() throws Excep when(channelFuture.addListener(any())).thenAnswer(invocation -> { @SuppressWarnings("unchecked") - io.netty.util.concurrent.GenericFutureListener listener = invocation.getArgument(0); + GenericFutureListener listener = invocation.getArgument(0); listenerCalled.set(true); // Simulate successful write listener.operationComplete(channelFuture); @@ -417,7 +418,7 @@ public void testAcquireDirectMemoryPermitsAndWriteAndFlushMultipleConcurrent() t when(ctx.writeAndFlush(any(ByteBuf.class))).thenReturn(channelFuture); when(channelFuture.addListener(any())).thenAnswer(invocation -> { @SuppressWarnings("unchecked") - io.netty.util.concurrent.GenericFutureListener listener = invocation.getArgument(0); + GenericFutureListener listener = invocation.getArgument(0); listener.operationComplete(channelFuture); return channelFuture; }); @@ -455,7 +456,7 @@ public void testAcquireDirectMemoryPermitsAndWriteAndFlushReleasesOnWriteFailure when(ctx.writeAndFlush(any(ByteBuf.class))).thenReturn(channelFuture); when(channelFuture.addListener(any())).thenAnswer(invocation -> { @SuppressWarnings("unchecked") - io.netty.util.concurrent.GenericFutureListener listener = invocation.getArgument(0); + GenericFutureListener listener = invocation.getArgument(0); // Simulate write failure when(channelFuture.isSuccess()).thenReturn(false); when(channelFuture.cause()).thenReturn(new RuntimeException("Write to socket failed")); From 7b8939210d4bf2481a2c6a3f38e67c0eee7fd860 Mon Sep 17 00:00:00 2001 From: Matteo Merli Date: Sun, 29 Mar 2026 17:13:35 -0700 Subject: [PATCH 3/4] [improve][test] Fix unused import in PartitionedProducerImplTest --- .../apache/pulsar/client/impl/PartitionedProducerImplTest.java | 1 - 1 file changed, 1 deletion(-) diff --git a/pulsar-client/src/test/java/org/apache/pulsar/client/impl/PartitionedProducerImplTest.java b/pulsar-client/src/test/java/org/apache/pulsar/client/impl/PartitionedProducerImplTest.java index 34faceaff81ad..43134d5d94cc9 100644 --- a/pulsar-client/src/test/java/org/apache/pulsar/client/impl/PartitionedProducerImplTest.java +++ b/pulsar-client/src/test/java/org/apache/pulsar/client/impl/PartitionedProducerImplTest.java @@ -45,7 +45,6 @@ import org.apache.pulsar.client.api.Message; import org.apache.pulsar.client.api.MessageRouter; import org.apache.pulsar.client.api.MessageRoutingMode; -import org.apache.pulsar.client.api.Producer; import org.apache.pulsar.client.api.Schema; import org.apache.pulsar.client.api.TopicMetadata; import org.apache.pulsar.client.impl.conf.ClientConfigurationData; From 96ecb43f3c45a4e241dca736e8c06238b6740595 Mon Sep 17 00:00:00 2001 From: Matteo Merli Date: Mon, 30 Mar 2026 06:42:13 -0700 Subject: [PATCH 4/4] [improve][test] Fix remaining checkstyle line-length violation in TxnLogBufferedWriterTest --- .../transaction/coordinator/impl/TxnLogBufferedWriterTest.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/pulsar-transaction/coordinator/src/test/java/org/apache/pulsar/transaction/coordinator/impl/TxnLogBufferedWriterTest.java b/pulsar-transaction/coordinator/src/test/java/org/apache/pulsar/transaction/coordinator/impl/TxnLogBufferedWriterTest.java index 3ec03dc9fd240..4e280a08a9309 100644 --- a/pulsar-transaction/coordinator/src/test/java/org/apache/pulsar/transaction/coordinator/impl/TxnLogBufferedWriterTest.java +++ b/pulsar-transaction/coordinator/src/test/java/org/apache/pulsar/transaction/coordinator/impl/TxnLogBufferedWriterTest.java @@ -471,7 +471,8 @@ public void testPendingScheduleTriggerTaskCount() throws Exception { // Mock managed ledger and write counter. MockedManagedLedger mockedManagedLedger = mockManagedLedgerWithWriteCounter(mlName); // Start tests. - TxnLogBufferedWriter txnLogBufferedWriter = new TxnLogBufferedWriter<>(mockedManagedLedger.managedLedger, + TxnLogBufferedWriter txnLogBufferedWriter = new TxnLogBufferedWriter<>( + mockedManagedLedger.managedLedger, threadPoolExecutor, transactionTimer, dataSerializer, 2, 1024 * 4, 1, true, DISABLED_BUFFERED_WRITER_METRICS); TxnLogBufferedWriter.AddDataCallback callback = Mockito.mock(TxnLogBufferedWriter.AddDataCallback.class);