Skip to content

Commit

Permalink
NIFI-14140 Applied PMD's UnusedLocalVariable across the code base and…
Browse files Browse the repository at this point in the history
… fixed all the violations.
  • Loading branch information
dan-s1 committed Jan 13, 2025
1 parent 25ca4b4 commit c78ef23
Show file tree
Hide file tree
Showing 85 changed files with 209 additions and 267 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,6 @@ public ConfigSchema(Map map, List<String> validationIssues) {
List<String> allControllerServiceIds = allProcessGroups.stream().flatMap(p -> p.getControllerServices().stream()).map(ControllerServiceSchema::getId).collect(Collectors.toList());
List<String> allFunnelIds = allProcessGroups.stream().flatMap(p -> p.getFunnels().stream()).map(FunnelSchema::getId).collect(Collectors.toList());
List<String> allConnectionIds = allConnectionSchemas.stream().map(ConnectionSchema::getId).collect(Collectors.toList());
List<String> allRemoteProcessGroupNames = allRemoteProcessGroups.stream().map(RemoteProcessGroupSchema::getName).collect(Collectors.toList());
List<String> allRemoteInputPortIds = allRemoteProcessGroups.stream().filter(r -> r.getInputPorts() != null)
.flatMap(r -> r.getInputPorts().stream()).map(RemotePortSchema::getId).collect(Collectors.toList());
List<String> allRemoteOutputPortIds = allRemoteProcessGroups.stream().filter(r -> r.getOutputPorts() != null)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,7 @@ public void testShouldVerifyExceptionThrownWhenInValidFormatPortValue() {
NiFiProperties properties = loadNiFiProperties("/NiFiProperties/conf/nifi.blank.properties", additionalProperties);

// Act
Integer clusterProtocolPort = properties.getClusterNodeProtocolPort();
properties.getClusterNodeProtocolPort();
assertThrows(NumberFormatException.class, () -> Integer.parseInt(portValue));
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,6 @@ public void testDeleteObjectS3Exception() {
runner.run(1);

runner.assertAllFlowFilesTransferred(DeleteS3Object.REL_FAILURE, 1);
ArgumentCaptor<DeleteObjectRequest> captureRequest = ArgumentCaptor.forClass(DeleteObjectRequest.class);
Mockito.verify(mockS3Client, Mockito.never()).deleteVersion(Mockito.any(DeleteVersionRequest.class));
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ public SystemtimeTypeNode(BinaryReader binaryReader, ChunkHeader chunkHeader, Bx
int year = binaryReader.readWord();
int month = binaryReader.readWord();
final int monthOfYear = month + 1;
int dayOfWeek = binaryReader.readWord();
binaryReader.readWord(); // dayOfWeek
int day = binaryReader.readWord();
int hour = binaryReader.readWord();
int minute = binaryReader.readWord();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ public List<ConfigVerificationResult> verify(final ConfigurationContext context,
.explanation("Successfully configured data source")
.build());

try (final Connection conn = getConnection(basicDataSource, kerberosUser)) {
try (final Connection ignored = getConnection(basicDataSource, kerberosUser)) {
results.add(new ConfigVerificationResult.Builder()
.verificationStepName("Establish Connection")
.outcome(SUCCESSFUL)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -769,7 +769,6 @@ public void testFileAcls() {

@Test
public void testYieldOnBadStateRestore() {
final Iterable<Blob> mockList = Collections.emptyList();

runner.getStateManager().setFailOnStateGet(Scope.CLUSTER, true);
runner.enqueue("test");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ public class FlowFileStreamUnpackerSequenceFileWriter extends SequenceFileWriter
@Override
protected void processInputStream(final InputStream stream, final FlowFile flowFileStreamPackedFlowFile, final Writer writer) throws IOException {
final FlowFileUnpackager unpackager = new FlowFileUnpackager();
try (final InputStream in = new BufferedInputStream(stream)) {
try (final InputStream ignored = new BufferedInputStream(stream)) {
while (unpackager.hasMoreData()) {
unpackager.unpackageFlowFile(stream, writer);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ public <K, V> boolean replace(final AtomicCacheEntry<K, V, Long> entry, final Se

final String key = serializeCacheEntryKey(entry.getKey(), keySerializer);

try (final HazelcastCache.HazelcastCacheEntryLock lock = cache.acquireLock(key)) {
try (final HazelcastCache.HazelcastCacheEntryLock ignored = cache.acquireLock(key)) {
final byte[] oldValue = cache.get(key);

if (oldValue == null && (entry.getRevision().isEmpty() || entry.getRevision().get() < STARTING_REVISION)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -330,7 +330,6 @@ public void onPropertyModified(final PropertyDescriptor descriptor, final String

@OnScheduled
public void onScheduled(final ProcessContext context) {
final KafkaConnectionService connectionService = context.getProperty(CONNECTION_SERVICE).asControllerService(KafkaConnectionService.class);
pollingContext = createPollingContext(context);
headerEncoding = Charset.forName(context.getProperty(HEADER_ENCODING).getValue());

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,7 @@ public void testZeroRecordInput() throws InitializationException {
assertEquals(0, testRunner.getCounterValue("Records Dropped").intValue());

final List<Record> written = recordWriter.getRecordsWritten();
assertEquals(0, written.size());
}

@Test
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@
import static org.apache.nifi.smb.common.SmbProperties.TIMEOUT;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.Mockito.mock;

import eu.rekawek.toxiproxy.model.ToxicDirection;
import java.util.HashMap;
Expand All @@ -38,7 +37,6 @@
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.nifi.components.PropertyDescriptor;
import org.apache.nifi.controller.ConfigurationContext;
import org.apache.nifi.util.MockConfigurationContext;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
Expand Down Expand Up @@ -94,7 +92,6 @@ public void shouldRescueAfterConnectionFailure() throws Exception {
writeFile("testDirectory/directory2/nested_directory/file", "content");
ContainerProxy sambaProxy = toxiproxy.getProxy("samba", 445);
SmbjClientProviderService smbjClientProviderService = new SmbjClientProviderService();
ConfigurationContext context = mock(ConfigurationContext.class);

Map<PropertyDescriptor, String> properties = new HashMap<>();
properties.put(HOSTNAME, sambaProxy.getContainerIpAddress());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,6 @@ public List<ConfigVerificationResult> verify(final ConfigurationContext context,

try {
final List<ParameterGroup> parameterGroups = fetchParameters(context);
final Set<String> parameterGroupNames = parameterGroups.stream().map(ParameterGroup::getGroupName).collect(Collectors.toSet());
final long parameterCount = parameterGroups.stream()
.flatMap(group -> group.getParameters().stream())
.count();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -717,7 +717,6 @@ public FlowFile replace(FlowFile flowFile, final ProcessSession session, final P
out.write(updatedValue.getBytes(charset));
});
} else {
final Pattern searchPattern = Pattern.compile(searchValue, Pattern.LITERAL);

flowFile = session.write(flowFile, new StreamReplaceCallback(charset, maxBufferSize, context.getProperty(LINE_BY_LINE_EVALUATION_MODE).getValue(),
(bw, oneLine) -> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -255,8 +255,6 @@ public void testSetAutoCommitFalseFailure() throws InitializationException, SQLE

LocalDate testDate1 = LocalDate.of(2021, 1, 26);
Date jdbcDate1 = Date.valueOf(testDate1); // in local TZ
LocalDate testDate2 = LocalDate.of(2021, 7, 26);
Date jdbcDate2 = Date.valueOf(testDate2); // in local TZ

parser.addRecord(1, "rec1", 101, jdbcDate1);

Expand Down Expand Up @@ -1221,7 +1219,6 @@ public void testUpdateMultipleSchemas(TestCase testCase) throws InitializationEx
runner.setProperty(PutDatabaseRecord.TABLE_NAME, "PERSONS");

// Set some existing records with different values for name and code
Exception e;
ResultSet rs;

stmt.execute("INSERT INTO SCHEMA1.PERSONS VALUES (1,'x1',101,null)");
Expand Down Expand Up @@ -1715,14 +1712,6 @@ public void testInsertWithDefaultMaxBatchSize() throws InitializationException,
public void testGenerateTableName() throws InitializationException, ProcessException {
setRunner(TestCaseEnum.DEFAULT_0.getTestCase());

final List<RecordField> fields = Arrays.asList(new RecordField("id", RecordFieldType.INT.getDataType()),
new RecordField("name", RecordFieldType.STRING.getDataType()),
new RecordField("code", RecordFieldType.INT.getDataType()),
new RecordField("non_existing", RecordFieldType.BOOLEAN.getDataType())
);

final RecordSchema schema = new SimpleRecordSchema(fields);

final TableSchema tableSchema = new TableSchema(
null,
null,
Expand Down Expand Up @@ -1831,9 +1820,6 @@ public void testInsertMismatchedNotCompatibleDataTypes() throws InitializationEx
parser.addSchemaField("code", RecordFieldType.INT);
parser.addSchemaField("dt", RecordFieldType.ARRAY.getArrayDataType(RecordFieldType.FLOAT.getDataType()).getFieldType());

LocalDate testDate1 = LocalDate.of(2021, 1, 26);
LocalDate testDate2 = LocalDate.of(2021, 7, 26);

parser.addRecord("1", "rec1", 101, Arrays.asList(1.0, 2.0));
parser.addRecord("2", "rec2", 102, Arrays.asList(3.0, 4.0));
parser.addRecord("3", "rec3", 103, null);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1104,7 +1104,6 @@ public void testInitialLoadStrategyStartAtCurrentMaximumValues() throws SQLExcep
// load test data to database
final Connection con = ((DBCPService) runner.getControllerService("dbcp")).getConnection();
Statement stmt = con.createStatement();
InputStream in;

try {
stmt.execute("drop table TEST_QUERY_DB_TABLE");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -563,7 +563,6 @@ public void invokeOnTriggerRecords(final Integer queryTimeout, final String quer

// ResultSet size will be 1x200x100 = 20 000 rows
// because of where PER.ID = ${person.id}
final int nrOfRows = 20000;

MockRecordWriter recordWriter = new MockRecordWriter(null, true, -1);
runner.addControllerService("writer", recordWriter);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,6 @@ public void testProcessor() {

testRunner.assertAllFlowFilesTransferred(ExtractText.REL_MATCH, 1);
final MockFlowFile out = testRunner.getFlowFilesForRelationship(ExtractText.REL_MATCH).get(0);
java.util.Map<String, String> attributes = out.getAttributes();
out.assertAttributeEquals("regex.result1.ALL", SAMPLE_STRING);
out.assertAttributeEquals("regex.result2.BAR1", "bar1");
out.assertAttributeEquals("regex.result3.BAR1", "bar1");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -141,19 +141,16 @@ public void testAttributes() throws IOException {
final Path targetPath = destFile.toPath();
Files.copy(inPath, targetPath);

boolean verifyLastModified = false;
try {
destFile.setLastModified(1000000000);
verifyLastModified = true;
} catch (Exception doNothing) {
} catch (Exception ignored) {
}

final TestRunner runner = TestRunners.newTestRunner(new GetFile());
runner.setProperty(GetFile.DIRECTORY, "target/test/data/in");
runner.run();

runner.assertAllFlowFilesTransferred(GetFile.REL_SUCCESS, 1);
final List<MockFlowFile> successFiles = runner.getFlowFilesForRelationship(GetFile.REL_SUCCESS);
//permissions are not verified as these are very environmentally specific
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ private List<File> listFiles(final File file) {
private void runNext() throws InterruptedException {
runner.clearTransferState();

final List<File> files = listFiles(testDir);
listFiles(testDir);
final Long lagMillis;
if (isMillisecondSupported) {
lagMillis = AbstractListProcessor.LISTING_LAG_MILLIS.get(TimeUnit.MILLISECONDS);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -352,7 +352,7 @@ private void assertMessagesReceived(final String[] sentData) throws Exception {

private void assertMessagesReceived(final String[] sentData, final int iterations) throws Exception {
for (int i = 0; i < iterations; i++) {
for (String item : sentData) {
for (String ignored : sentData) {
final ByteArrayMessage message = messages.take();
assertNotNull(message, String.format("Message [%d] not found", i));
assertTrue(Arrays.asList(sentData).contains(new String(message.getMessage())));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -353,7 +353,7 @@ public List<ConfigVerificationResult> verify(final ConfigurationContext context,
.explanation("Successfully configured data source")
.build());

try (final Connection conn = getConnection(hikariDataSource, kerberosUser)) {
try (final Connection ignored = getConnection(hikariDataSource, kerberosUser)) {
results.add(new ConfigVerificationResult.Builder()
.verificationStepName("Establish Connection")
.outcome(SUCCESSFUL)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ void testPerformanceOfSchemaInferenceWithTimestamp() throws IOException {

for (int i = 0; i < 10_000; i++) {
try (final InputStream in = new ByteArrayInputStream(manyCopies)) {
final RecordSchema schema = accessStrategy.getSchema(null, in, null);
accessStrategy.getSchema(null, in, null);
}
}

Expand Down Expand Up @@ -107,7 +107,7 @@ void testPerformanceOfSchemaInferenceWithoutTimestamp() throws IOException {
final InferSchemaAccessStrategy<?> accessStrategy = new InferSchemaAccessStrategy<>((var, content) -> new JsonRecordSource(content),
noTimestampInference, Mockito.mock(ComponentLog.class));

final RecordSchema schema = accessStrategy.getSchema(null, in, null);
accessStrategy.getSchema(null, in, null);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,6 @@ private RecordSchema inferSchema(final String filename, final String contentFiel
final SchemaInferenceEngine<XmlNode> schemaInference = new XmlSchemaInference(timeValueInference);
final InferSchemaAccessStrategy<XmlNode> inferStrategy = new InferSchemaAccessStrategy<>(xmlSourceFactory, schemaInference, Mockito.mock(ComponentLog.class));

final RecordSchema schema;
try (final InputStream fis = new FileInputStream(file);
final InputStream in = new BufferedInputStream(fis)) {
return inferStrategy.getSchema(Collections.emptyMap(), in, null);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,6 @@ public class TestUser {
public void testSimpleCreation() {
final String identifier = "1";
final String identity = "user1";
final String group1 = "group1";
final String group2 = "group2";

final User user = new User.Builder()
.identifier(identifier)
Expand Down Expand Up @@ -57,8 +55,6 @@ public void testMissingIdentity() {
public void testFromUser() {
final String identifier = "1";
final String identity = "user1";
final String group1 = "group1";
final String group2 = "group2";

final User user = new User.Builder()
.identifier(identifier)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ public void testOverwriteEmptyFile() throws IOException {
try {
assertTrue(tocFile.createNewFile());

try (final StandardTocWriter writer = new StandardTocWriter(tocFile, false, false)) {
try (final StandardTocWriter ignored = new StandardTocWriter(tocFile, false, false)) {
}
} finally {
FileUtils.deleteFile(tocFile, false);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ public AccessPolicyProviderInvocationHandler(final AccessPolicyProvider accessPo

@Override
public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
try (final NarCloseable narCloseable = NarCloseable.withComponentNarLoader(classLoader)) {
try (final NarCloseable ignored = NarCloseable.withComponentNarLoader(classLoader)) {
if (getUserGroupProviderMethod.equals(method)) {
final UserGroupProvider userGroupProvider = (UserGroupProvider) method.invoke(accessPolicyProvider, args);
if (userGroupProvider == null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ public AuthorizerInvocationHandler(final Authorizer authorizer, final ClassLoade

@Override
public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
try (final NarCloseable narCloseable = NarCloseable.withComponentNarLoader(classLoader)) {
try (final NarCloseable ignored = NarCloseable.withComponentNarLoader(classLoader)) {
if (getAccessPolicyProviderMethod.equals(method)) {
final AccessPolicyProvider accessPolicyProvider = (AccessPolicyProvider) method.invoke(authorizer, args);
if (accessPolicyProvider == null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ public UserGroupProviderInvocationHandler(final UserGroupProvider userGroupProvi

@Override
public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
try (final NarCloseable narCloseable = NarCloseable.withComponentNarLoader(classLoader)) {
try (final NarCloseable ignored = NarCloseable.withComponentNarLoader(classLoader)) {
return method.invoke(userGroupProvider, args);
} catch (final InvocationTargetException e) {
// If the proxied instance throws an Exception, it'll be wrapped in an InvocationTargetException. We want
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,6 @@ public void testRoundTripConnectionResponse() throws JAXBException {
JaxbProtocolUtils.JAXB_CONTEXT.createMarshaller().marshal(msg, baos);
final Object unmarshalled = JaxbProtocolUtils.JAXB_CONTEXT.createUnmarshaller().unmarshal(new ByteArrayInputStream(baos.toByteArray()));
assertTrue(unmarshalled instanceof ConnectionResponseMessage);
final ConnectionResponseMessage unmarshalledMsg = (ConnectionResponseMessage) unmarshalled;

final ComponentRevisionSnapshot receivedSnapshot = msg.getConnectionResponse().getComponentRevisions();
final List<ComponentRevision> revisions = receivedSnapshot.getComponentRevisions();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,6 @@ public class TestProcessorEndpointMerger {

@Test
public void testMergeValidationErrors() {
final ProcessorEndpointMerger merger = new ProcessorEndpointMerger();
final Map<String, Set<NodeIdentifier>> validationErrorMap = new HashMap<>();

final NodeIdentifier nodeId1234 = new NodeIdentifier("1234", "localhost", 9000, "localhost", 9001, "localhost", 9002, 9003, false);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,9 +58,8 @@ public class FileBasedClusterNodeFirewallTest {
*/
@BeforeAll
public static void ensureBadHostsDoNotWork() {
final InetAddress ip;
try {
ip = InetAddress.getByName(NONEXISTENT_HOSTNAME);
InetAddress.getByName(NONEXISTENT_HOSTNAME);
} catch (final UnknownHostException uhe) {
badHostsDoNotResolve = true;
}
Expand Down
Loading

0 comments on commit c78ef23

Please sign in to comment.