    void publish(final FlowFile flowFile, final RecordReader reader, final RecordSetWriterFactory writerFactory, final RecordSchema schema,
        final String messageKeyField, final String topic) throws IOException {
        if (tracker == null) {
            tracker = new InFlightMessageTracker();
        }

        final ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);

        Record record;
        final RecordSet recordSet = reader.createRecordSet();
        int recordCount = 0;

        try (final RecordSetWriter writer = writerFactory.createWriter(logger, schema, flowFile, baos)) {
            while ((record = recordSet.next()) != null) {
                recordCount++;
                baos.reset();
                writer.write(record);

                final byte[] messageContent = baos.toByteArray();
                final String key = messageKeyField == null ? null : record.getAsString(messageKeyField);
                final byte[] messageKey = (key == null) ? null : key.getBytes(StandardCharsets.UTF_8);

                publish(flowFile, messageKey, messageContent, topic, tracker);

                if (tracker.isFailed(flowFile)) {
                    // If we have a failure, don't try to send anything else.
                    return;
                }
            }

            if (recordCount == 0) {
                tracker.trackEmpty(flowFile);
            }
        } catch (final TokenTooLargeException ttle) {
            tracker.fail(flowFile, ttle);
        } catch (final SchemaNotFoundException snfe) {
            throw new IOException(snfe);
        } catch (final Exception e) {
            tracker.fail(flowFile, e);
            poison();
            throw e;
        }
    }

    void publish(final FlowFile flowFile, final RecordReader reader, final RecordWriter writer, final String messageKeyField, final String topic) throws IOException {
        if (tracker == null) {
            tracker = new InFlightMessageTracker();
        }

        final ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);

        Record record;
        final RecordSet recordSet = reader.createRecordSet();
        int recordCount = 0;

        try {
            while ((record = recordSet.next()) != null) {
                recordCount++;
                baos.reset();
                writer.write(record, baos);

                final byte[] messageContent = baos.toByteArray();
                final String key = messageKeyField == null ? null : record.getAsString(messageKeyField);
                final byte[] messageKey = (key == null) ? null : key.getBytes(StandardCharsets.UTF_8);

                publish(flowFile, messageKey, messageContent, topic, tracker);

                if (tracker.isFailed(flowFile)) {
                    // If we have a failure, don't try to send anything else.
                    return;
                }
            }

            if (recordCount == 0) {
                tracker.trackEmpty(flowFile);
            }
        } catch (final TokenTooLargeException ttle) {
            tracker.fail(flowFile, ttle);
        } catch (final Exception e) {
            tracker.fail(flowFile, e);
            poison();
            throw e;
        }
    }

Try With Resources try(final RecordSetWriter writer=writerFactory.createWriter(logger,schema,flowFile,baos)) in method package publish(flowFile FlowFile, reader RecordReader, writerFactory RecordSetWriterFactory, schema RecordSchema, messageKeyField String, topic String) : void from class org.apache.nifi.processors.kafka.pubsub.PublisherLease


                            @Override
                            public void process(final OutputStream out) throws IOException {
                                try (final RecordSetWriter resultSetWriter = resultSetWriterFactory.createWriter(getLogger(), recordSchema, outFlowFile, out)) {
                                    final ResultSetRecordSet resultSet = new ResultSetRecordSet(rs);
                                    writeResultRef.set(resultSetWriter.write(resultSet));
                                    mimeTypeRef.set(resultSetWriter.getMimeType());
                                } catch (final Exception e) {
                                    throw new IOException(e);
                                }
                            }

                            @Override
                            public void process(final OutputStream out) throws IOException {
                                try {
                                    final ResultSetRecordSet recordSet = new ResultSetRecordSet(rs);
                                    writeResultRef.set(resultSetWriter.write(recordSet, out));
                                } catch (final Exception e) {
                                    throw new IOException(e);
                                }
                            }

Try With Resources try(final RecordSetWriter resultSetWriter=resultSetWriterFactory.createWriter(getLogger(),recordSchema,outFlowFile,out)) in method public process(out OutputStream) : void from class org.apache.nifi.processors.standard.QueryRecord.onTrigger.write.new OutputStreamCallback


    /**
     * Validates the connection string and returns the storage account. The connection string must be in the Azure connection string format.
     *
     * @param storageConnectionString
     *            Connection string for the storage service or the emulator
     * @return The newly created CloudStorageAccount object
     *
     */
    private static CloudStorageAccount createStorageAccountFromConnectionString(String storageConnectionString) throws IllegalArgumentException, URISyntaxException, InvalidKeyException {
        CloudStorageAccount storageAccount;
        try {
            storageAccount = CloudStorageAccount.parse(storageConnectionString);
        } catch (IllegalArgumentException | URISyntaxException | InvalidKeyException e) {
            throw e;
        }
        return storageAccount;
    }

    /**
     * Validates the connection string and returns the storage account. The connection string must be in the Azure connection string format.
     *
     * @param storageConnectionString
     *            Connection string for the storage service or the emulator
     * @return The newly created CloudStorageAccount object
     *
     */
    protected static CloudStorageAccount createStorageAccountFromConnectionString(String storageConnectionString) throws IllegalArgumentException, URISyntaxException, InvalidKeyException {
        CloudStorageAccount storageAccount;
        try {
            storageAccount = CloudStorageAccount.parse(storageConnectionString);
        } catch (IllegalArgumentException | URISyntaxException e) {
            throw e;
        } catch (InvalidKeyException e) {
            throw e;
        }
        return storageAccount;
    }

Merge Catch [catch(IllegalArgumentException|URISyntaxException e), catch(InvalidKeyException e)] to catch(IllegalArgumentException|URISyntaxException|InvalidKeyException e) in method private createStorageAccountFromConnectionString(storageConnectionString String) : CloudStorageAccount from class org.apache.nifi.processors.azure.AbstractAzureProcessor


    @Override
    public void onTrigger(ProcessContext context, ProcessSession session) throws ProcessException {
        FlowFile flowFile = session.get();
        if (flowFile == null) {
            return;
        }

        final long startNanos = System.nanoTime();

        String containerName = context.getProperty(AzureConstants.CONTAINER).evaluateAttributeExpressions(flowFile).getValue();
        String blobPath = context.getProperty(BLOB).evaluateAttributeExpressions(flowFile).getValue();

        try {
            CloudStorageAccount storageAccount = createStorageConnection(context, flowFile);
            CloudBlobClient blobClient = storageAccount.createCloudBlobClient();
            CloudBlobContainer container = blobClient.getContainerReference(containerName);

            final Map<String, String> attributes = new HashMap<>();
            final CloudBlob blob = container.getBlockBlobReference(blobPath);

            // TODO - we may be able do fancier things with ranges and
            // distribution of download over threads, investigate
            flowFile = session.write(flowFile, os -> {
                try {
                    blob.download(os);
                } catch (StorageException e) {
                    throw new IOException(e);
                }
            });

            long length = blob.getProperties().getLength();
            attributes.put("azure.length", String.valueOf(length));

            if (!attributes.isEmpty()) {
                flowFile = session.putAllAttributes(flowFile, attributes);
            }

            session.transfer(flowFile, REL_SUCCESS);
            final long transferMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNanos);
            session.getProvenanceReporter().fetch(flowFile, blob.getSnapshotQualifiedUri().toString(), transferMillis);

        } catch (IllegalArgumentException | URISyntaxException | StorageException e1) {
            flowFile = session.penalize(flowFile);
            session.transfer(flowFile, REL_FAILURE);
        }
    }

    @Override
    public void onTrigger(ProcessContext context, ProcessSession session) throws ProcessException {
        FlowFile flowFile = session.get();
        if (flowFile == null) {
            return;
        }

        final long startNanos = System.nanoTime();

        String containerName = context.getProperty(AzureConstants.CONTAINER).evaluateAttributeExpressions(flowFile).getValue();
        String blobPath = context.getProperty(BLOB).evaluateAttributeExpressions(flowFile).getValue();

        try {
            CloudStorageAccount storageAccount = createStorageConnection(context, flowFile);
            CloudBlobClient blobClient = storageAccount.createCloudBlobClient();
            CloudBlobContainer container = blobClient.getContainerReference(containerName);

            final Map<String, String> attributes = new HashMap<>();
            final CloudBlob blob = container.getBlockBlobReference(blobPath);

            // TODO - we may be able do fancier things with ranges and
            // distribution of download over threads, investigate
            flowFile = session.write(flowFile, new OutputStreamCallback() {
                @Override
                public void process(OutputStream os) throws IOException {
                    try {
                        blob.download(os);
                    } catch (StorageException e) {
                        throw new IOException(e);
                    }
                }
            });

            long length = blob.getProperties().getLength();
            attributes.put("azure.length", String.valueOf(length));

            if (!attributes.isEmpty()) {
                flowFile = session.putAllAttributes(flowFile, attributes);
            }

            session.transfer(flowFile, REL_SUCCESS);
            final long transferMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNanos);
            session.getProvenanceReporter().fetch(flowFile, blob.getSnapshotQualifiedUri().toString(), transferMillis);

        } catch (IllegalArgumentException | URISyntaxException | StorageException e1) {
            flowFile = session.penalize(flowFile);
            session.transfer(flowFile, REL_FAILURE);
        }
    }

Replace Anonymous With Lambda org.apache.nifi.processors.azure.storage.FetchAzureBlobStorage.onTrigger.write.new OutputStreamCallback with os -> {tryblob.download(os); in method public onTrigger(context ProcessContext, session ProcessSession) : void from class org.apache.nifi.processors.azure.storage.FetchAzureBlobStorage


    public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
        FlowFile flowFile = session.get();
        if (flowFile == null) {
            return;
        }

        final long startNanos = System.nanoTime();

        String containerName = context.getProperty(AzureConstants.CONTAINER).evaluateAttributeExpressions(flowFile).getValue();

        String blobPath = context.getProperty(BLOB).evaluateAttributeExpressions(flowFile).getValue();

        try {
            CloudStorageAccount storageAccount = createStorageConnection(context, flowFile);
            CloudBlobClient blobClient = storageAccount.createCloudBlobClient();
            CloudBlobContainer container = blobClient.getContainerReference(containerName);

            CloudBlob blob = container.getBlockBlobReference(blobPath);

            final Map<String, String> attributes = new HashMap<>();
            long length = flowFile.getSize();
            session.read(flowFile, rawIn -> {
                InputStream in = rawIn;
                if (!(in instanceof BufferedInputStream)) {
                    // do not double-wrap
                    in = new BufferedInputStream(rawIn);
                }

                try {
                    blob.upload(in, length);
                    BlobProperties properties = blob.getProperties();
                    attributes.put("azure.container", containerName);
                    attributes.put("azure.primaryUri", blob.getSnapshotQualifiedUri().toString());
                    attributes.put("azure.etag", properties.getEtag());
                    attributes.put("azure.length", String.valueOf(length));
                    attributes.put("azure.timestamp", String.valueOf(properties.getLastModified()));
                } catch (StorageException | URISyntaxException e) {
                    throw new IOException(e);
                }
            });

            if (!attributes.isEmpty()) {
                flowFile = session.putAllAttributes(flowFile, attributes);
            }
            session.transfer(flowFile, REL_SUCCESS);

            final long transferMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNanos);
            session.getProvenanceReporter().send(flowFile, blob.getSnapshotQualifiedUri().toString(), transferMillis);

        } catch (IllegalArgumentException | URISyntaxException | StorageException e) {
            getLogger().error("Failed to put Azure blob {}", new Object[]{blobPath}, e);
            flowFile = session.penalize(flowFile);
            session.transfer(flowFile, REL_FAILURE);
        }

    }

    public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
        FlowFile flowFile = session.get();
        if (flowFile == null) {
            return;
        }

        final long startNanos = System.nanoTime();

        String containerName = context.getProperty(AzureConstants.CONTAINER).evaluateAttributeExpressions(flowFile).getValue();

        String blobPath = context.getProperty(BLOB).evaluateAttributeExpressions(flowFile).getValue();

        try {
            CloudStorageAccount storageAccount = createStorageConnection(context, flowFile);
            CloudBlobClient blobClient = storageAccount.createCloudBlobClient();
            CloudBlobContainer container = blobClient.getContainerReference(containerName);

            CloudBlob blob = container.getBlockBlobReference(blobPath);

            final Map<String, String> attributes = new HashMap<>();
            long length = flowFile.getSize();
            session.read(flowFile, new InputStreamCallback() {
                @Override
                public void process(final InputStream rawIn) throws IOException {
                    final InputStream in = new BufferedInputStream(rawIn);
                    try {
                        blob.upload(in, length);
                        BlobProperties properties = blob.getProperties();
                        attributes.put("azure.container", containerName);
                        attributes.put("azure.primaryUri", blob.getSnapshotQualifiedUri().toString());
                        attributes.put("azure.etag", properties.getEtag());
                        attributes.put("azure.length", String.valueOf(length));
                        attributes.put("azure.timestamp", String.valueOf(properties.getLastModified()));
                    } catch (StorageException | URISyntaxException e) {
                        throw new IOException(e);
                    }
                }
            });

            if (!attributes.isEmpty()) {
                flowFile = session.putAllAttributes(flowFile, attributes);
            }
            session.transfer(flowFile, REL_SUCCESS);

            final long transferMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNanos);
            session.getProvenanceReporter().send(flowFile, blob.getSnapshotQualifiedUri().toString(), transferMillis);

        } catch (IllegalArgumentException | URISyntaxException | StorageException e) {
            getLogger().error("Failed to put Azure blob {}", new Object[]{blobPath}, e);
            flowFile = session.penalize(flowFile);
            session.transfer(flowFile, REL_FAILURE);
        }

    }

Replace Anonymous With Lambda org.apache.nifi.processors.azure.storage.PutAzureBlobStorage.onTrigger.read.new InputStreamCallback with rawIn -> {InputStream in=rawIn; in method public onTrigger(context ProcessContext, session ProcessSession) : void from class org.apache.nifi.processors.azure.storage.PutAzureBlobStorage


    @Override
    public void notify(NotificationContext context, NotificationType notificationType, String subject, String message) throws NotificationFailedException {
        try {
            final RequestBody requestBody = RequestBody.create(MediaType.parse("text/plain"), message);

            Request.Builder requestBuilder = new Request.Builder()
                    .post(requestBody)
                    .url(urlReference.get());

            Map<PropertyDescriptor, String> configuredProperties = context.getProperties();

            for(PropertyDescriptor propertyDescriptor: configuredProperties.keySet()) {
                if (propertyDescriptor.isDynamic()) {
                    String propertyValue = context.getProperty(propertyDescriptor).evaluateAttributeExpressions().getValue();
                    requestBuilder = requestBuilder.addHeader(propertyDescriptor.getDisplayName(), propertyValue);
                }
            }

            final Request request = requestBuilder
                    .addHeader(NOTIFICATION_SUBJECT_KEY, subject)
                    .addHeader(NOTIFICATION_TYPE_KEY, notificationType.name())
                    .build();

            final OkHttpClient httpClient = httpClientReference.get();

            final Call call = httpClient.newCall(request);
             try (final Response response = call.execute()) {

                 if (!response.isSuccessful()) {
                     throw new NotificationFailedException("Failed to send Http Notification. Received an unsuccessful status code response '" + response.code() + "'. The message was '" +
                             response.message() + "'");
                 }
             }
        } catch (NotificationFailedException e){
            throw e;
        } catch (Exception e) {
            throw new NotificationFailedException("Failed to send Http Notification", e);
        }
    }

    @Override
    public void notify(NotificationContext context, NotificationType notificationType, String subject, String message) throws NotificationFailedException {
        try {
            final RequestBody requestBody = RequestBody.create(MediaType.parse("text/plain"), message);

            Request.Builder requestBuilder = new Request.Builder()
                    .post(requestBody)
                    .url(urlReference.get());

            Map<PropertyDescriptor, String> configuredProperties = context.getProperties();

            for(PropertyDescriptor propertyDescriptor: configuredProperties.keySet()) {
                if (propertyDescriptor.isDynamic()) {
                    String propertyValue = context.getProperty(propertyDescriptor).evaluateAttributeExpressions().getValue();
                    requestBuilder = requestBuilder.addHeader(propertyDescriptor.getDisplayName(), propertyValue);
                }
            }

            final Request request = requestBuilder
                    .addHeader(NOTIFICATION_SUBJECT_KEY, subject)
                    .addHeader(NOTIFICATION_TYPE_KEY, notificationType.name())
                    .build();

            final OkHttpClient httpClient = httpClientReference.get();

            final Call call = httpClient.newCall(request);
            final Response response = call.execute();

            if (!response.isSuccessful()) {
                throw new NotificationFailedException("Failed to send Http Notification. Received an unsuccessful status code response '" + response.code() +"'. The message was '" +
                        response.message() + "'");
            }
        } catch (NotificationFailedException e){
            throw e;
        } catch (Exception e) {
            throw new NotificationFailedException("Failed to send Http Notification", e);
        }
    }

Try With Resources try(final Response response=call.execute()) in method public notify(context NotificationContext, notificationType NotificationType, subject String, message String) : void from class org.apache.nifi.bootstrap.notification.http.HttpNotificationService


    protected Map<String,String> getDefaultMaxValueProperties(final Map<PropertyDescriptor, String> properties){
        final Map<String,String> defaultMaxValues = new HashMap<>();

        for (final Map.Entry<PropertyDescriptor, String> entry : properties.entrySet()) {
            final String key = entry.getKey().getName();

            if(!key.startsWith(INTIIAL_MAX_VALUE_PROP_START)) {
                continue;
            }

            defaultMaxValues.put(key.substring(INTIIAL_MAX_VALUE_PROP_START.length()), entry.getValue());
        }

        return defaultMaxValues;
    }

    protected Map<String,String> getDefaultMaxValueProperties(final Map<PropertyDescriptor, String> properties){
        final Map<String,String> defaultMaxValues = new HashMap<String, String>();

        for (final Map.Entry<PropertyDescriptor, String> entry : properties.entrySet()) {
            final String key = entry.getKey().getName();

            if(!key.startsWith(INTIIAL_MAX_VALUE_PROP_START)) {
                continue;
            }

            defaultMaxValues.put(key.substring(INTIIAL_MAX_VALUE_PROP_START.length()), entry.getValue());
        }

        return defaultMaxValues;
    }

Replace Generic With Diamond HashMap<String,String> with HashMap<> in method protected getDefaultMaxValueProperties(properties Map<PropertyDescriptor,String>) : Map<String,String> from class org.apache.nifi.processors.standard.QueryDatabaseTable


    /**
     * This method creates all resources needed for the script processor to function, such as script engines,
     * script file reloader threads, etc.
     */
    public void createResources() {
        descriptors = new ArrayList<>();
        // The following is required for JRuby, should be transparent to everything else.
        // Note this is not done in a ScriptEngineConfigurator, as it is too early in the lifecycle. The
        // setting must be there before the factories/engines are loaded.
        System.setProperty("org.jruby.embed.localvariable.behavior", "persistent");

        // Create list of available engines
        ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
        List<ScriptEngineFactory> scriptEngineFactories = scriptEngineManager.getEngineFactories();
        if (scriptEngineFactories != null) {
            scriptEngineFactoryMap = new HashMap<>(scriptEngineFactories.size());
            List<AllowableValue> engineList = new LinkedList<>();
            for (ScriptEngineFactory factory : scriptEngineFactories) {
                engineList.add(new AllowableValue(factory.getLanguageName()));
                scriptEngineFactoryMap.put(factory.getLanguageName(), factory);
            }

            // Sort the list by name so the list always looks the same.
            Collections.sort(engineList, (o1, o2) -> {
                if (o1 == null) {
                    return o2 == null ? 0 : 1;
                }
                if (o2 == null) {
                    return -1;
                }
                return o1.getValue().compareTo(o2.getValue());
            });

            AllowableValue[] engines = engineList.toArray(new AllowableValue[engineList.size()]);

            SCRIPT_ENGINE = new PropertyDescriptor.Builder()
                    .name("Script Engine")
                    .required(true)
                    .description("The engine to execute scripts")
                    .allowableValues(engines)
                    .defaultValue(engines[0].getValue())
                    .required(true)
                    .expressionLanguageSupported(false)
                    .build();
            descriptors.add(SCRIPT_ENGINE);
        }

        descriptors.add(ScriptingComponentUtils.SCRIPT_FILE);
        descriptors.add(ScriptingComponentUtils.SCRIPT_BODY);
        descriptors.add(ScriptingComponentUtils.MODULES);

        isInitialized.set(true);
    }

    /**
     * This method creates all resources needed for the script processor to function, such as script engines,
     * script file reloader threads, etc.
     */
    protected void createResources() {
        descriptors = new ArrayList<>();
        // The following is required for JRuby, should be transparent to everything else.
        // Note this is not done in a ScriptEngineConfigurator, as it is too early in the lifecycle. The
        // setting must be there before the factories/engines are loaded.
        System.setProperty("org.jruby.embed.localvariable.behavior", "persistent");

        // Create list of available engines
        ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
        List<ScriptEngineFactory> scriptEngineFactories = scriptEngineManager.getEngineFactories();
        if (scriptEngineFactories != null) {
            scriptEngineFactoryMap = new HashMap<>(scriptEngineFactories.size());
            List<AllowableValue> engineList = new LinkedList<>();
            for (ScriptEngineFactory factory : scriptEngineFactories) {
                engineList.add(new AllowableValue(factory.getLanguageName()));
                scriptEngineFactoryMap.put(factory.getLanguageName(), factory);
            }

            // Sort the list by name so the list always looks the same.
            Collections.sort(engineList, new Comparator<AllowableValue>() {
                @Override
                public int compare(AllowableValue o1, AllowableValue o2) {
                    if (o1 == null) {
                        return o2 == null ? 0 : 1;
                    }
                    if (o2 == null) {
                        return -1;
                    }
                    return o1.getValue().compareTo(o2.getValue());
                }
            });

            AllowableValue[] engines = engineList.toArray(new AllowableValue[engineList.size()]);

            SCRIPT_ENGINE = new PropertyDescriptor.Builder()
                    .name("Script Engine")
                    .required(true)
                    .description("The engine to execute scripts")
                    .allowableValues(engines)
                    .defaultValue(engines[0].getValue())
                    .required(true)
                    .expressionLanguageSupported(false)
                    .build();
            descriptors.add(SCRIPT_ENGINE);
        }

        descriptors.add(SCRIPT_FILE);
        descriptors.add(SCRIPT_BODY);
        descriptors.add(MODULES);

        isInitialized.set(true);
    }

Replace Anonymous With Lambda org.apache.nifi.processors.script.AbstractScriptProcessor.createResources.sort.new Comparator<AllowableValue> with (o1, o2) -> {if(o1 == null){return o2 == null ? 0 : 1; in method public createResources() : void from class org.apache.nifi.processors.script.ScriptingComponentHelper


    /**
     *
     */
    private void invokeDisable(ConfigurationContext configContext) {
        try (final NarCloseable nc = NarCloseable.withComponentNarLoader(getControllerServiceImplementation().getClass(), getIdentifier())) {
            ReflectionUtils.invokeMethodsWithAnnotation(OnDisabled.class, StandardControllerServiceNode.this.getControllerServiceImplementation(), configContext);
        } catch (Exception e) {
            final Throwable cause = e instanceof InvocationTargetException ? e.getCause() : e;
            final ComponentLog componentLog = new SimpleProcessLogger(getIdentifier(), StandardControllerServiceNode.this);
            componentLog.error("Failed to invoke @OnDisabled method due to {}", cause);
            LOG.error("Failed to invoke @OnDisabled method of {} due to {}", getControllerServiceImplementation(), cause.toString());
        }
    }

    /**
     *
     */
    private void invokeDisable(ConfigurationContext configContext) {
        try {
            ReflectionUtils.invokeMethodsWithAnnotation(OnDisabled.class, StandardControllerServiceNode.this.getControllerServiceImplementation(), configContext);
        } catch (Exception e) {
            final Throwable cause = e instanceof InvocationTargetException ? e.getCause() : e;
            final ComponentLog componentLog = new SimpleProcessLogger(getIdentifier(), StandardControllerServiceNode.this);
            componentLog.error("Failed to invoke @OnDisabled method due to {}", cause);
            LOG.error("Failed to invoke @OnDisabled method of {} due to {}", getControllerServiceImplementation(), cause.toString());
        }
    }

Try With Resources try(final NarCloseable nc=NarCloseable.withComponentNarLoader(getControllerServiceImplementation().getClass(),getIdentifier())) in method private invokeDisable(configContext ConfigurationContext) : void from class org.apache.nifi.controller.service.StandardControllerServiceNode


    /**
     * Disposes the message by converting it to a {@link FlowFile} transferring
     * it to the REL_SUCCESS relationship.
     */
    private void transfer(Message emailMessage, ProcessContext context, ProcessSession processSession) {
        long start = System.nanoTime();
        FlowFile flowFile = processSession.create();

        flowFile = processSession.append(flowFile, out -> {
            try {
                emailMessage.writeTo(out);
            } catch (MessagingException e) {
                throw new IOException(e);
            }
        });

        long executionDuration = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start);

        String fromAddressesString = "";
        try {
            Address[] fromAddresses = emailMessage.getFrom();
            if (fromAddresses != null) {
                fromAddressesString = Arrays.asList(fromAddresses).toString();
            }
        } catch (MessagingException e) {
            this.logger.warn("Failed to retrieve 'From' attribute from Message.");
        }

        processSession.getProvenanceReporter().receive(flowFile, this.displayUrl, "Received message from " + fromAddressesString, executionDuration);
        this.getLogger().info("Successfully received {} from {} in {} millis", new Object[]{flowFile, fromAddressesString, executionDuration});
        processSession.transfer(flowFile, REL_SUCCESS);

        try {
            emailMessage.setFlag(Flags.Flag.DELETED, this.shouldSetDeleteFlag);
        } catch (MessagingException e) {
            this.logger.warn("Failed to set DELETE Flag on the message", e);
            this.getLogger().warn("Failed to set DELETE Flag on the message");
        }
    }

    /**
     * Disposes the message by converting it to a {@link FlowFile} transferring
     * it to the REL_SUCCESS relationship.
     */
    private void transfer(Message emailMessage, ProcessContext context, ProcessSession processSession) {
        long start = System.nanoTime();
        FlowFile flowFile = processSession.create();

        flowFile = processSession.append(flowFile, new OutputStreamCallback() {
            @Override
            public void process(final OutputStream out) throws IOException {
                try {
                    StreamUtils.copy(emailMessage.getInputStream(), out);
                } catch (MessagingException e) {
                    throw new IOException(e);
                }
            }
        });

        long executionDuration = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start);

        String fromAddressesString = "";
        try {
            Address[] fromAddresses = emailMessage.getFrom();
            if (fromAddresses != null) {
                fromAddressesString = Arrays.asList(fromAddresses).toString();
            }
        } catch (MessagingException e) {
            this.logger.warn("Failed to retrieve 'From' attribute from Message.");
        }

        processSession.getProvenanceReporter().receive(flowFile, this.displayUrl, "Received message from " + fromAddressesString, executionDuration);
        this.getLogger().info("Successfully received {} from {} in {} millis", new Object[]{flowFile, fromAddressesString, executionDuration});
        processSession.transfer(flowFile, REL_SUCCESS);

        try {
            emailMessage.setFlag(Flags.Flag.DELETED, this.shouldSetDeleteFlag);
        } catch (MessagingException e) {
            this.logger.warn("Failed to set DELETE Flag on the message", e);
            this.getLogger().warn("Failed to set DELETE Flag on the message");
        }
    }

Replace Anonymous With Lambda org.apache.nifi.processors.email.AbstractEmailProcessor.transfer.append.new OutputStreamCallback with out -> {tryemailMessage.writeTo(out); in method private transfer(emailMessage Message, context ProcessContext, processSession ProcessSession) : void from class org.apache.nifi.processors.email.AbstractEmailProcessor


    @Override
    public void onTrigger(ProcessContext context, ProcessSession session) throws ProcessException {
        final ConsumerPool pool = getConsumerPool(context);
        if (pool == null) {
            context.yield();
            return;
        }

        try (final ConsumerLease lease = pool.obtainConsumer(session)) {
            if (lease == null) {
                context.yield();
                return;
            }
            try {
                while (this.isScheduled() && lease.continuePolling()) {
                    lease.poll();
                }
                if (this.isScheduled() && !lease.commit()) {
                    context.yield();
                }
            } catch (final KafkaException kex) {
                getLogger().error("Exception while interacting with Kafka so will close the lease {} due to {}",
                        new Object[]{lease, kex}, kex);
            } catch (final Throwable t) {
                getLogger().error("Exception while processing data from kafka so will close the lease {} due to {}",
                        new Object[]{lease, t}, t);
            }
        }
    }

    @Override
    public void onTrigger(ProcessContext context, ProcessSession session) throws ProcessException {
        final long startTimeNanos = System.nanoTime();
        final ConsumerPool pool = getConsumerPool(context);
        if (pool == null) {
            context.yield();
            return;
        }
        final Map<TopicPartition, List<ConsumerRecord<byte[], byte[]>>> partitionRecordMap = new HashMap<>();

        try (final ConsumerLease lease = pool.obtainConsumer()) {
            try {
                if (lease == null) {
                    context.yield();
                    return;
                }

                final boolean foundData = gatherDataFromKafka(lease, partitionRecordMap, context);
                if (!foundData) {
                    session.rollback();
                    return;
                }

                writeSessionData(context, session, partitionRecordMap, startTimeNanos);
                //At-least once commit handling (if order is reversed it is at-most once)
                session.commit();
                commitOffsets(lease, partitionRecordMap);
            } catch (final KafkaException ke) {
                lease.poison();
                getLogger().error("Problem while accessing kafka consumer " + ke, ke);
                context.yield();
                session.rollback();
            }
        }
    }

Try With Resources try(final ConsumerLease lease=pool.obtainConsumer(session)) in method public onTrigger(context ProcessContext, session ProcessSession) : void from class org.apache.nifi.processors.kafka.pubsub.ConsumeKafka_0_10


    @Override
    public void onTrigger(final ProcessContext context, final ProcessSession session) {
        final FlowFile original = session.get();
        if (original == null) {
            return;
        }

        final int depth = context.getProperty(SPLIT_DEPTH).asInteger();
        final ComponentLog logger = getLogger();

        final List<FlowFile> splits = new ArrayList<>();
        final String fragmentIdentifier = UUID.randomUUID().toString();
        final AtomicInteger numberOfRecords = new AtomicInteger(0);
        final XmlSplitterSaxParser parser = new XmlSplitterSaxParser(xmlTree -> {
            FlowFile split = session.create(original);
            split = session.write(split, out -> out.write(xmlTree.getBytes("UTF-8")));
            split = session.putAttribute(split, "fragment.identifier", fragmentIdentifier);
            split = session.putAttribute(split, "fragment.index", Integer.toString(numberOfRecords.getAndIncrement()));
            split = session.putAttribute(split, "segment.original.filename", split.getAttribute(CoreAttributes.FILENAME.key()));
            splits.add(split);
        }, depth);

        final AtomicBoolean failed = new AtomicBoolean(false);
        session.read(original, rawIn -> {
            try (final InputStream in = new BufferedInputStream(rawIn)) {
                SAXParser saxParser = null;
                try {
                    saxParser = saxParserFactory.newSAXParser();
                    final XMLReader reader = saxParser.getXMLReader();
                    reader.setContentHandler(parser);
                    reader.parse(new InputSource(in));
                } catch (final ParserConfigurationException | SAXException e) {
                    logger.error("Unable to parse {} due to {}", new Object[]{original, e});
                    failed.set(true);
                }
            }
        });

        if (failed.get()) {
            session.transfer(original, REL_FAILURE);
            session.remove(splits);
        } else {
            splits.forEach((split) -> {
                split = session.putAttribute(split, "fragment.count", Integer.toString(numberOfRecords.get()));
                session.transfer(split, REL_SPLIT);
            });

            session.transfer(original, REL_ORIGINAL);
            logger.info("Split {} into {} FlowFiles", new Object[]{original, splits.size()});
        }
    }

    @Override
    public void onTrigger(final ProcessContext context, final ProcessSession session) {
        final FlowFile original = session.get();
        if (original == null) {
            return;
        }

        final int depth = context.getProperty(SPLIT_DEPTH).asInteger();
        final ComponentLog logger = getLogger();

        final List<FlowFile> splits = new ArrayList<>();
        final XmlSplitterSaxParser parser = new XmlSplitterSaxParser(new XmlElementNotifier() {
            @Override
            public void onXmlElementFound(final String xmlTree) {
                FlowFile split = session.create(original);
                split = session.write(split, new OutputStreamCallback() {
                    @Override
                    public void process(final OutputStream out) throws IOException {
                        out.write(xmlTree.getBytes("UTF-8"));
                    }
                });
                splits.add(split);
            }
        }, depth);

        final AtomicBoolean failed = new AtomicBoolean(false);
        session.read(original, new InputStreamCallback() {
            @Override
            public void process(final InputStream rawIn) throws IOException {
                try (final InputStream in = new BufferedInputStream(rawIn)) {
                    SAXParser saxParser = null;
                    try {
                        saxParser = saxParserFactory.newSAXParser();
                        final XMLReader reader = saxParser.getXMLReader();
                        reader.setContentHandler(parser);
                        reader.parse(new InputSource(in));
                    } catch (final ParserConfigurationException | SAXException e) {
                        logger.error("Unable to parse {} due to {}", new Object[]{original, e});
                        failed.set(true);
                    }
                }
            }
        });

        if (failed.get()) {
            session.transfer(original, REL_FAILURE);
            session.remove(splits);
        } else {
            session.transfer(splits, REL_SPLIT);
            session.transfer(original, REL_ORIGINAL);
            logger.info("Split {} into {} FlowFiles", new Object[]{original, splits.size()});
        }
    }

Replace Anonymous With Lambda org.apache.nifi.processors.standard.SplitXml.onTrigger.read.new InputStreamCallback with rawIn -> {try(final InputStream in=new BufferedInputStream(rawIn))SAXParser saxParser=null; in method public onTrigger(context ProcessContext, session ProcessSession) : void from class org.apache.nifi.processors.standard.SplitXml


    protected FilenameFilter getJarFilenameFilter(){
        return  (dir, name) -> name != null && name.endsWith(".jar");
    }

    protected FilenameFilter getJarFilenameFilter(){
        return  new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                return (name != null && name.endsWith(".jar"));
            }
        };
    }

Replace Anonymous With Lambda org.apache.nifi.util.file.classloader.TestClassLoaderUtils.getJarFilenameFilter.new FilenameFilter with (dir, name) -> name != null && name.endsWith(".jar") in method protected getJarFilenameFilter() : FilenameFilter from class org.apache.nifi.util.file.classloader.TestClassLoaderUtils


        @Override
        public void run() {
            try (final NarCloseable narCloseable = NarCloseable.withFrameworkNar()) {
                if (heartbeatsSuspended.get()) {
                    return;
                }

                final HeartbeatMessage message = createHeartbeatMessage();
                if (message == null) {
                    heartbeatLogger.debug("No heartbeat to send");
                    return;
                }

                final long sendStart = System.nanoTime();
                heartbeater.send(message);

                final long sendNanos = System.nanoTime() - sendStart;
                final long sendMillis = TimeUnit.NANOSECONDS.toMillis(sendNanos);

                String heartbeatAddress;
                try {
                    heartbeatAddress = heartbeater.getHeartbeatAddress();
                } catch (final IOException ioe) {
                    heartbeatAddress = "Cluster Coordinator (could not determine socket address)";
                }

                heartbeatLogger.info("Heartbeat created at {} and sent to {} at {}; send took {} millis",
                        dateFormatter.format(new Date(message.getHeartbeat().getCreatedTimestamp())),
                        heartbeatAddress,
                        dateFormatter.format(new Date()),
                        sendMillis);
            } catch (final UnknownServiceAddressException usae) {
                if (heartbeatLogger.isDebugEnabled()) {
                    heartbeatLogger.debug(usae.getMessage());
                }
            } catch (final Throwable ex) {
                heartbeatLogger.warn("Failed to send heartbeat due to: " + ex);
                if (heartbeatLogger.isDebugEnabled()) {
                    heartbeatLogger.warn("", ex);
                }
            }
        }

        @Override
        public void run() {
            try {
                if (heartbeatsSuspended.get()) {
                    return;
                }

                final HeartbeatMessage message = createHeartbeatMessage();
                if (message == null) {
                    heartbeatLogger.debug("No heartbeat to send");
                    return;
                }

                final long sendStart = System.nanoTime();
                heartbeater.send(message);

                final long sendNanos = System.nanoTime() - sendStart;
                final long sendMillis = TimeUnit.NANOSECONDS.toMillis(sendNanos);

                String heartbeatAddress;
                try {
                    heartbeatAddress = heartbeater.getHeartbeatAddress();
                } catch (final IOException ioe) {
                    heartbeatAddress = "Cluster Coordinator (could not determine socket address)";
                }

                heartbeatLogger.info("Heartbeat created at {} and sent to {} at {}; send took {} millis",
                        dateFormatter.format(new Date(message.getHeartbeat().getCreatedTimestamp())),
                        heartbeatAddress,
                        dateFormatter.format(new Date()),
                        sendMillis);
            } catch (final UnknownServiceAddressException usae) {
                if (heartbeatLogger.isDebugEnabled()) {
                    heartbeatLogger.debug(usae.getMessage());
                }
            } catch (final Throwable ex) {
                heartbeatLogger.warn("Failed to send heartbeat due to: " + ex);
                if (heartbeatLogger.isDebugEnabled()) {
                    heartbeatLogger.warn("", ex);
                }
            }
        }

Try With Resources try(final NarCloseable narCloseable=NarCloseable.withFrameworkNar()) in method public run() : void from class org.apache.nifi.controller.FlowController.HeartbeatSendTask


    /**
     * Validates that one or more files exist, as specified in a single property.
     */
    public static Validator createMultipleFilesExistValidator() {
        return (subject, input, context) -> {
            final String[] files = input.split("\\s*,\\s*");
            for (String filename : files) {
                try {
                    final File file = new File(filename.trim());
                    final boolean valid = file.exists() && file.isFile();
                    if (!valid) {
                        final String message = "File " + file + " does not exist or is not a file";
                        return new ValidationResult.Builder().subject(subject).input(input).valid(false).explanation(message).build();
                    }
                } catch (SecurityException e) {
                    final String message = "Unable to access " + filename + " due to " + e.getMessage();
                    return new ValidationResult.Builder().subject(subject).input(input).valid(false).explanation(message).build();
                }
            }
            return new ValidationResult.Builder().subject(subject).input(input).valid(true).build();
        };
    }

    /**
     * Validates that one or more files exist, as specified in a single property.
     */
    public static Validator createMultipleFilesExistValidator() {
        return new Validator() {

            @Override
            public ValidationResult validate(String subject, String input, ValidationContext context) {
                final String[] files = input.split(",");
                for (String filename : files) {
                    try {
                        final File file = new File(filename.trim());
                        final boolean valid = file.exists() && file.isFile();
                        if (!valid) {
                            final String message = "File " + file + " does not exist or is not a file";
                            return new ValidationResult.Builder().subject(subject).input(input).valid(false).explanation(message).build();
                        }
                    } catch (SecurityException e) {
                        final String message = "Unable to access " + filename + " due to " + e.getMessage();
                        return new ValidationResult.Builder().subject(subject).input(input).valid(false).explanation(message).build();
                    }
                }
                return new ValidationResult.Builder().subject(subject).input(input).valid(true).build();
            }

        };
    }

Replace Anonymous With Lambda org.apache.nifi.util.hive.HiveJdbcCommon.createMultipleFilesExistValidator.new Validator with (subject, input, context) -> {final String[] files=input.split("\\s*,\\s*"); in method public createMultipleFilesExistValidator() : Validator from class org.apache.nifi.util.hive.HiveUtils


    @Override
    public void onTrigger(final ProcessContext context, final ProcessSessionFactory sessionFactory) throws ProcessException {
        ProcessSession session = sessionFactory.createSession();
        FlowFile fileToProcess = null;

        final ComponentLog logger = getLogger();

        final DBCPService dbcpService = context.getProperty(DBCP_SERVICE).asControllerService(DBCPService.class);
        final DatabaseAdapter dbAdapter = dbAdapters.get(context.getProperty(DB_TYPE).getValue());
        final String tableName = context.getProperty(TABLE_NAME).getValue();
        final String columnNames = context.getProperty(COLUMN_NAMES).getValue();
        final String maxValueColumnNames = context.getProperty(MAX_VALUE_COLUMN_NAMES).getValue();
        final Integer fetchSize = context.getProperty(FETCH_SIZE).asInteger();

        final StateManager stateManager = context.getStateManager();
        final StateMap stateMap;

        try {
            stateMap = stateManager.getState(Scope.CLUSTER);
        } catch (final IOException ioe) {
            getLogger().error("Failed to retrieve observed maximum values from the State Manager. Will not perform "
                    + "query until this is accomplished.", ioe);
            context.yield();
            return;
        }
        // Make a mutable copy of the current state property map. This will be updated by the result row callback, and eventually
        // set as the current state map (after the session has been committed)
        final Map<String, String> statePropertyMap = new HashMap<>(stateMap.toMap());

        List<String> maxValueColumnNameList = StringUtils.isEmpty(maxValueColumnNames)
                ? null
                : Arrays.asList(maxValueColumnNames.split("\\s*,\\s*"));
        final String selectQuery = getQuery(dbAdapter, tableName, columnNames, maxValueColumnNameList, stateMap);
        final StopWatch stopWatch = new StopWatch(true);

        try (final Connection con = dbcpService.getConnection();
             final Statement st = con.createStatement()) {

            if (fetchSize != null && fetchSize > 0) {
                try {
                    st.setFetchSize(fetchSize);
                } catch (SQLException se) {
                    // Not all drivers support this, just log the error (at debug level) and move on
                    logger.debug("Cannot set fetch size to {} due to {}", new Object[]{fetchSize, se.getLocalizedMessage()}, se);
                }
            }

            final Integer queryTimeout = context.getProperty(QUERY_TIMEOUT).asTimePeriod(TimeUnit.SECONDS).intValue();
            st.setQueryTimeout(queryTimeout); // timeout in seconds

            final AtomicLong nrOfRows = new AtomicLong(0L);

            fileToProcess = session.create();
            fileToProcess = session.write(fileToProcess, out -> {
                try {
                    logger.debug("Executing query {}", new Object[]{selectQuery});
                    final ResultSet resultSet = st.executeQuery(selectQuery);
                    // Max values will be updated in the state property map by the callback
                    final MaxValueResultSetRowCollector maxValCollector = new MaxValueResultSetRowCollector(statePropertyMap, dbAdapter);
                    nrOfRows.set(JdbcCommon.convertToAvroStream(resultSet, out, tableName, maxValCollector));

                } catch (final SQLException e) {
                    throw new ProcessException("Error during database query or conversion of records to Avro", e);
                }
            });

            if (nrOfRows.get() > 0) {
                // set attribute how many rows were selected
                fileToProcess = session.putAttribute(fileToProcess, RESULT_ROW_COUNT, String.valueOf(nrOfRows.get()));

                logger.info("{} contains {} Avro records; transferring to 'success'",
                        new Object[]{fileToProcess, nrOfRows.get()});
                String jdbcURL = "DBCPService";
                try {
                    DatabaseMetaData databaseMetaData = con.getMetaData();
                    if (databaseMetaData != null) {
                        jdbcURL = databaseMetaData.getURL();
                    }
                } catch (SQLException se) {
                    // Ignore and use default JDBC URL. This shouldn't happen unless the driver doesn't implement getMetaData() properly
                }
                session.getProvenanceReporter().receive(fileToProcess, jdbcURL, stopWatch.getElapsed(TimeUnit.MILLISECONDS));
                session.transfer(fileToProcess, REL_SUCCESS);
            } else {
                // If there were no rows returned, don't send the flowfile
                session.remove(fileToProcess);
                context.yield();
            }

        } catch (final ProcessException | SQLException e) {
            logger.error("Unable to execute SQL select query {} due to {}", new Object[]{selectQuery, e});
            if (fileToProcess != null) {
                session.remove(fileToProcess);
            }
            context.yield();
        } finally {
            session.commit();
            try {
                // Update the state
                stateManager.setState(statePropertyMap, Scope.CLUSTER);
            } catch (IOException ioe) {
                getLogger().error("{} failed to update State Manager, maximum observed values will not be recorded", new Object[]{this, ioe});
            }
        }
    }

    @Override
    public void onTrigger(final ProcessContext context, final ProcessSessionFactory sessionFactory) throws ProcessException {
        ProcessSession session = sessionFactory.createSession();
        FlowFile fileToProcess = null;

        final ComponentLog logger = getLogger();

        final DBCPService dbcpService = context.getProperty(DBCP_SERVICE).asControllerService(DBCPService.class);
        final String tableName = context.getProperty(TABLE_NAME).getValue();
        final String columnNames = context.getProperty(COLUMN_NAMES).getValue();
        final String maxValueColumnNames = context.getProperty(MAX_VALUE_COLUMN_NAMES).getValue();
        final String preProcessStrategy = context.getProperty(SQL_PREPROCESS_STRATEGY).getValue();
        final Integer fetchSize = context.getProperty(FETCH_SIZE).asInteger();

        final StateManager stateManager = context.getStateManager();
        final StateMap stateMap;

        try {
            stateMap = stateManager.getState(Scope.CLUSTER);
        } catch (final IOException ioe) {
            getLogger().error("Failed to retrieve observed maximum values from the State Manager. Will not perform "
                    + "query until this is accomplished.", ioe);
            context.yield();
            return;
        }
        // Make a mutable copy of the current state property map. This will be updated by the result row callback, and eventually
        // set as the current state map (after the session has been committed)
        final Map<String, String> statePropertyMap = new HashMap<>(stateMap.toMap());

        final String selectQuery = getQuery(tableName, columnNames, getColumns(maxValueColumnNames), stateMap, preProcessStrategy);
        final StopWatch stopWatch = new StopWatch(true);

        try (final Connection con = dbcpService.getConnection();
             final Statement st = con.createStatement()) {

            if (fetchSize != null && fetchSize > 0) {
                try {
                    st.setFetchSize(fetchSize);
                } catch (SQLException se) {
                    // Not all drivers support this, just log the error (at debug level) and move on
                    logger.debug("Cannot set fetch size to {} due to {}", new Object[]{fetchSize, se.getLocalizedMessage()}, se);
                }
            }

            final Integer queryTimeout = context.getProperty(QUERY_TIMEOUT).asTimePeriod(TimeUnit.SECONDS).intValue();
            st.setQueryTimeout(queryTimeout); // timeout in seconds

            final AtomicLong nrOfRows = new AtomicLong(0L);

            fileToProcess = session.create();
            fileToProcess = session.write(fileToProcess, new OutputStreamCallback() {
                @Override
                public void process(final OutputStream out) throws IOException {
                    try {
                        logger.debug("Executing query {}", new Object[]{selectQuery});
                        final ResultSet resultSet = st.executeQuery(selectQuery);
                        // Max values will be updated in the state property map by the callback
                        final MaxValueResultSetRowCollector maxValCollector = new MaxValueResultSetRowCollector(statePropertyMap, preProcessStrategy);
                        nrOfRows.set(JdbcCommon.convertToAvroStream(resultSet, out, tableName, maxValCollector));

                    } catch (final SQLException e) {
                        throw new ProcessException("Error during database query or conversion of records to Avro", e);
                    }
                }
            });

            if (nrOfRows.get() > 0) {
                // set attribute how many rows were selected
                fileToProcess = session.putAttribute(fileToProcess, RESULT_ROW_COUNT, String.valueOf(nrOfRows.get()));

                logger.info("{} contains {} Avro records; transferring to 'success'",
                        new Object[]{fileToProcess, nrOfRows.get()});
                String jdbcURL = "DBCPService";
                try {
                    DatabaseMetaData databaseMetaData = con.getMetaData();
                    if (databaseMetaData != null) {
                        jdbcURL = databaseMetaData.getURL();
                    }
                } catch (SQLException se) {
                    // Ignore and use default JDBC URL. This shouldn't happen unless the driver doesn't implement getMetaData() properly
                }
                session.getProvenanceReporter().receive(fileToProcess, jdbcURL, stopWatch.getElapsed(TimeUnit.MILLISECONDS));
                session.transfer(fileToProcess, REL_SUCCESS);
            } else {
                // If there were no rows returned, don't send the flowfile
                session.remove(fileToProcess);
                context.yield();
            }

        } catch (final ProcessException | SQLException e) {
            logger.error("Unable to execute SQL select query {} due to {}", new Object[]{selectQuery, e});
            if (fileToProcess != null) {
                session.remove(fileToProcess);
            }
            context.yield();
        } finally {
            session.commit();
            try {
                // Update the state
                stateManager.setState(statePropertyMap, Scope.CLUSTER);
            } catch (IOException ioe) {
                getLogger().error("{} failed to update State Manager, maximum observed values will not be recorded", new Object[]{this, ioe});
            }
        }
    }

Replace Anonymous With Lambda org.apache.nifi.processors.standard.QueryDatabaseTable.onTrigger.write.new OutputStreamCallback with out -> {trylogger.debug("Executing query {}",new Object[]{selectQuery}); in method public onTrigger(context ProcessContext, sessionFactory ProcessSessionFactory) : void from class org.apache.nifi.processors.standard.QueryDatabaseTable


        @Override
        public String swapOut(List<FlowFileRecord> flowFiles, FlowFileQueue flowFileQueue) throws IOException {
            swapOutCalledCount++;
            final String location = UUID.randomUUID().toString();
            swappedOut.put(location, new ArrayList<>(flowFiles));
            return location;
        }

        @Override
        public String swapOut(List<FlowFileRecord> flowFiles, FlowFileQueue flowFileQueue) throws IOException {
            swapOutCalledCount++;
            final String location = UUID.randomUUID().toString();
            swappedOut.put(location, new ArrayList<FlowFileRecord>(flowFiles));
            return location;
        }

Replace Generic With Diamond ArrayList<FlowFileRecord> with ArrayList<> in method public swapOut(flowFiles List<FlowFileRecord>, flowFileQueue FlowFileQueue) : String from class org.apache.nifi.controller.TestStandardFlowFileQueue.TestSwapManager


        @Override
        public List<String> recoverSwapLocations(FlowFileQueue flowFileQueue) throws IOException {
            return new ArrayList<>(swappedOut.keySet());
        }

        @Override
        public List<String> recoverSwapLocations(FlowFileQueue flowFileQueue) throws IOException {
            return new ArrayList<String>(swappedOut.keySet());
        }

Replace Generic With Diamond ArrayList<String> with ArrayList<> in method public recoverSwapLocations(flowFileQueue FlowFileQueue) : List<String> from class org.apache.nifi.controller.TestStandardFlowFileQueue.TestSwapManager


        public TestFlowFile(final long size) {
            this(new HashMap<>(), size);
        }

        public TestFlowFile(final long size) {
            this(new HashMap<String, String>(), size);
        }

Replace Generic With Diamond HashMap<String,String> with HashMap<> in method public TestFlowFile(size long) from class org.apache.nifi.controller.TestStandardFlowFileQueue.TestFlowFile


    @Override
    public void refreshFlowContents() throws CommunicationsException {
        // check to see if we know whether we pointing to a local cluster or not -
        // we must know this before we attempt to update since querying the cluster
        // will cause a deadlock if we are in the context of another replicated request
        if (pointsToCluster.get() == null) {
            return;
        }

        if (pointsToCluster.get()) {
            refreshFlowContentsFromLocal();
            return;
        }

        if (targetIsUnreachable.get()) {
            return;
        }

        try {
            // perform the request
            final ControllerDTO dto;
            try (
                final SiteToSiteRestApiClient apiClient = getSiteToSiteRestApiClient();
            ){
                dto = apiClient.getController();
            } catch (IOException e) {
                writeLock.lock();
                try {
                    for (final Iterator<StandardRemoteGroupPort> iter = inputPorts.values().iterator(); iter.hasNext();) {
                        final StandardRemoteGroupPort inputPort = iter.next();
                        if (!inputPort.hasIncomingConnection()) {
                            iter.remove();
                        }
                    }

                    for (final Iterator<StandardRemoteGroupPort> iter = outputPorts.values().iterator(); iter.hasNext();) {
                        final StandardRemoteGroupPort outputPort = iter.next();
                        if (outputPort.getConnections().isEmpty()) {
                            iter.remove();
                        }
                    }
                } finally {
                    writeLock.unlock();
                }

                throw new CommunicationsException("Unable to communicate with Remote NiFi at URI " + apiUri + " due to: " + e.getMessage());
            }

            writeLock.lock();
            try {
                if (dto.getInputPorts() != null) {
                    setInputPorts(convertRemotePort(dto.getInputPorts()));
                }
                if (dto.getOutputPorts() != null) {
                    setOutputPorts(convertRemotePort(dto.getOutputPorts()));
                }

                // set the controller details
                setTargetId(dto.getId());
                setName(dto.getName());
                setComments(dto.getComments());

                // get the component counts
                int inputPortCount = 0;
                if (dto.getInputPortCount() != null) {
                    inputPortCount = dto.getInputPortCount();
                }
                int outputPortCount = 0;
                if (dto.getOutputPortCount() != null) {
                    outputPortCount = dto.getOutputPortCount();
                }
                int runningCount = 0;
                if (dto.getRunningCount() != null) {
                    runningCount = dto.getRunningCount();
                }
                int stoppedCount = 0;
                if (dto.getStoppedCount() != null) {
                    stoppedCount = dto.getStoppedCount();
                }
                int invalidCount = 0;
                if (dto.getInvalidCount() != null) {
                    invalidCount = dto.getInvalidCount();
                }
                int disabledCount = 0;
                if (dto.getDisabledCount() != null) {
                    disabledCount = dto.getDisabledCount();
                }

                int activeRemotePortCount = 0;
                if (dto.getActiveRemotePortCount() != null) {
                    activeRemotePortCount = dto.getActiveRemotePortCount();
                }

                int inactiveRemotePortCount = 0;
                if (dto.getInactiveRemotePortCount() != null) {
                    inactiveRemotePortCount = dto.getInactiveRemotePortCount();
                }

                this.listeningPort = dto.getRemoteSiteListeningPort();
                this.listeningHttpPort = dto.getRemoteSiteHttpListeningPort();
                this.destinationSecure = dto.isSiteToSiteSecure();

                final ProcessGroupCounts newCounts = new ProcessGroupCounts(inputPortCount, outputPortCount,
                        runningCount, stoppedCount, invalidCount, disabledCount, activeRemotePortCount, inactiveRemotePortCount);
                setCounts(newCounts);
                this.refreshContentsTimestamp = System.currentTimeMillis();
            } finally {
                writeLock.unlock();
            }
        } catch (final ClientHandlerException | UniformInterfaceException e) {
            throw new CommunicationsException(e);
        }
    }

    @Override
    public void refreshFlowContents() throws CommunicationsException {
        // check to see if we know whether we pointing to a local cluster or not -
        // we must know this before we attempt to update since querying the cluster
        // will cause a deadlock if we are in the context of another replicated request
        if (pointsToCluster.get() == null) {
            return;
        }

        if (pointsToCluster.get()) {
            refreshFlowContentsFromLocal();
            return;
        }

        if (targetIsUnreachable.get()) {
            return;
        }

        final RemoteNiFiUtils utils = new RemoteNiFiUtils(isWebApiSecure() ? sslContext : null);
        final String uriVal = apiUri.toString() + SITE_TO_SITE_URI_PATH;
        URI uri;
        try {
            uri = new URI(uriVal);
        } catch (final URISyntaxException e) {
            throw new CommunicationsException("Invalid URI: " + uriVal);
        }

        try {
            // perform the request
            final ClientResponse response = utils.get(uri, getCommunicationsTimeout(TimeUnit.MILLISECONDS));

            if (!Response.Status.Family.SUCCESSFUL.equals(response.getStatusInfo().getFamily())) {
                writeLock.lock();
                try {
                    for (final Iterator<StandardRemoteGroupPort> iter = inputPorts.values().iterator(); iter.hasNext();) {
                        final StandardRemoteGroupPort inputPort = iter.next();
                        if (!inputPort.hasIncomingConnection()) {
                            iter.remove();
                        }
                    }

                    for (final Iterator<StandardRemoteGroupPort> iter = outputPorts.values().iterator(); iter.hasNext();) {
                        final StandardRemoteGroupPort outputPort = iter.next();
                        if (outputPort.getConnections().isEmpty()) {
                            iter.remove();
                        }
                    }
                } finally {
                    writeLock.unlock();
                }

                // consume the entity entirely
                response.getEntity(String.class);
                throw new CommunicationsException("Unable to communicate with Remote NiFi at URI " + uriVal + ". Got HTTP Error Code "
                        + response.getStatus() + ": " + response.getStatusInfo().getReasonPhrase());
            }

            final ControllerEntity entity = response.getEntity(ControllerEntity.class);
            final ControllerDTO dto = entity.getController();

            writeLock.lock();
            try {
                if (dto.getInputPorts() != null) {
                    setInputPorts(convertRemotePort(dto.getInputPorts()));
                }
                if (dto.getOutputPorts() != null) {
                    setOutputPorts(convertRemotePort(dto.getOutputPorts()));
                }

                // set the controller details
                setTargetId(dto.getId());
                setName(dto.getName());
                setComments(dto.getComments());

                // get the component counts
                int inputPortCount = 0;
                if (dto.getInputPortCount() != null) {
                    inputPortCount = dto.getInputPortCount();
                }
                int outputPortCount = 0;
                if (dto.getOutputPortCount() != null) {
                    outputPortCount = dto.getOutputPortCount();
                }
                int runningCount = 0;
                if (dto.getRunningCount() != null) {
                    runningCount = dto.getRunningCount();
                }
                int stoppedCount = 0;
                if (dto.getStoppedCount() != null) {
                    stoppedCount = dto.getStoppedCount();
                }
                int invalidCount = 0;
                if (dto.getInvalidCount() != null) {
                    invalidCount = dto.getInvalidCount();
                }
                int disabledCount = 0;
                if (dto.getDisabledCount() != null) {
                    disabledCount = dto.getDisabledCount();
                }

                int activeRemotePortCount = 0;
                if (dto.getActiveRemotePortCount() != null) {
                    activeRemotePortCount = dto.getActiveRemotePortCount();
                }

                int inactiveRemotePortCount = 0;
                if (dto.getInactiveRemotePortCount() != null) {
                    inactiveRemotePortCount = dto.getInactiveRemotePortCount();
                }

                this.listeningPort = dto.getRemoteSiteListeningPort();
                this.destinationSecure = dto.isSiteToSiteSecure();

                final ProcessGroupCounts newCounts = new ProcessGroupCounts(inputPortCount, outputPortCount,
                        runningCount, stoppedCount, invalidCount, disabledCount, activeRemotePortCount, inactiveRemotePortCount);
                setCounts(newCounts);
                this.refreshContentsTimestamp = System.currentTimeMillis();
            } finally {
                writeLock.unlock();
            }
        } catch (final ClientHandlerException | UniformInterfaceException e) {
            throw new CommunicationsException(e);
        }
    }

Try With Resources try(final SiteToSiteRestApiClient apiClient=getSiteToSiteRestApiClient()) in method public refreshFlowContents() : void from class org.apache.nifi.remote.StandardRemoteProcessGroup


    /**
     * Creates a component using the optimistic locking manager.
     *
     * @param componentDto the DTO that will be used to create the component
     * @param daoCreation A Supplier that will create the NiFi Component to use
     * @param dtoCreation a Function that will convert the NiFi Component into a corresponding DTO
     *
     * @param <D> the DTO Type
     * @param <C> the NiFi Component Type
     *
     * @return a RevisionUpdate that represents the updated configuration
     */
    private <D, C> RevisionUpdate<D> createComponent(final ComponentDTO componentDto,
        final Supplier<C> daoCreation, final Function<C, D> dtoCreation) {

        final String modifier = NiFiUserUtils.getNiFiUserName();

        // ensure id is set
        if (StringUtils.isBlank(componentDto.getId())) {
            componentDto.setId(UUID.randomUUID().toString());
        }

        final String groupId = componentDto.getParentGroupId();
        return revisionManager.get(groupId, rev -> {
            // ensure access to process group
            final ProcessGroup parent = processGroupDAO.getProcessGroup(groupId);
            parent.authorize(authorizer, RequestAction.WRITE);

            // add the component
            final C component = daoCreation.get();

            // save the flow
            controllerFacade.save();

            final D dto = dtoCreation.apply(component);
            final FlowModification lastMod = new FlowModification(new Revision(0L, rev.getClientId(), componentDto.getId()), modifier);
            return new StandardRevisionUpdate<D>(dto, lastMod);
        });
    }

    /**
     * Creates a component using the optimistic locking manager.
     *
     * @param componentDto the DTO that will be used to create the component
     * @param daoCreation A Supplier that will create the NiFi Component to use
     * @param dtoCreation a Function that will convert the NiFi Component into a corresponding DTO
     *
     * @param <D> the DTO Type
     * @param <C> the NiFi Component Type
     *
     * @return a RevisionUpdate that represents the updated configuration
     */
    private <D, C> RevisionUpdate<D> createComponent(final ComponentDTO componentDto,
        final Supplier<C> daoCreation, final Function<C, D> dtoCreation) {

        final String modifier = NiFiUserUtils.getNiFiUserName();

        // ensure id is set
        if (StringUtils.isBlank(componentDto.getId())) {
            componentDto.setId(UUID.randomUUID().toString());
        }

        final String groupId = componentDto.getParentGroupId();
        return revisionManager.get(groupId, new ReadOnlyRevisionCallback<RevisionUpdate<D>>() {
            @Override
            public RevisionUpdate<D> withRevision(final Revision revision) {
                // ensure access to process group
                final ProcessGroup parent = processGroupDAO.getProcessGroup(groupId);
                parent.authorize(authorizer, RequestAction.WRITE);

                // add the component
                final C component = daoCreation.get();

                // save the flow
                controllerFacade.save();

                final D dto = dtoCreation.apply(component);
                final FlowModification lastMod = new FlowModification(new Revision(0L, revision.getClientId(), componentDto.getId()), modifier);
                return new StandardRevisionUpdate<D>(dto, lastMod);
            }
        });
    }

Replace Anonymous With Lambda org.apache.nifi.web.StandardNiFiServiceFacade.createComponent.get.new ReadOnlyRevisionCallback<RevisionUpdate<D>> with rev -> {final ProcessGroup parent=processGroupDAO.getProcessGroup(groupId); in method private createComponent(componentDto ComponentDTO, daoCreation Supplier<C>, dtoCreation Function<C,D>) : RevisionUpdate<D> from class org.apache.nifi.web.StandardNiFiServiceFacade


    @Override
    public Set<ConnectionEntity> getConnections(String groupId) {
        return revisionManager.get(groupId, rev -> {
            final ProcessGroup group = processGroupDAO.getProcessGroup(groupId);
            group.authorize(authorizer, RequestAction.READ);

            final Set<Connection> connections = connectionDAO.getConnections(groupId);
            final Set<String> connectionIds = connections.stream().map(connection -> connection.getIdentifier()).collect(Collectors.toSet());
            return revisionManager.get(connectionIds, () -> {
                return connections.stream()
                    .map(connection -> {
                        final RevisionDTO revision = dtoFactory.createRevisionDTO(revisionManager.getRevision(connection.getIdentifier()));
                        final AccessPolicyDTO accessPolicy = dtoFactory.createAccessPolicyDto(connection);
                        final ConnectionStatusDTO status = dtoFactory.createConnectionStatusDto(controllerFacade.getConnectionStatus(connection.getIdentifier()));
                        return entityFactory.createConnectionEntity(dtoFactory.createConnectionDto(connection), revision, accessPolicy, status);
                    })
                    .collect(Collectors.toSet());
            });
        });
    }

    @Override
    public Set<ConnectionEntity> getConnections(String groupId) {
        return revisionManager.get(groupId, new ReadOnlyRevisionCallback<Set<ConnectionEntity>>() {
            @Override
            public Set<ConnectionEntity> withRevision(Revision revision) {
                final ProcessGroup group = processGroupDAO.getProcessGroup(groupId);
                group.authorize(authorizer, RequestAction.READ);

                final Set<Connection> connections = connectionDAO.getConnections(groupId);
                final Set<String> connectionIds = connections.stream().map(connection -> connection.getIdentifier()).collect(Collectors.toSet());
                return revisionManager.get(connectionIds, () -> {
                    final Set<ConnectionEntity> connectionEntities = new LinkedHashSet<>();
                    for (Connection connection : connectionDAO.getConnections(groupId)) {
                        connectionEntities.add(entityFactory.createConnectionEntity(dtoFactory.createConnectionDto(connection), null, dtoFactory.createAccessPolicyDto(connection)));
                    }
                    return connectionEntities;
                });

            }
        });
    }

Replace Anonymous With Lambda org.apache.nifi.web.StandardNiFiServiceFacade.getConnections.get.new ReadOnlyRevisionCallback<Set<ConnectionEntity>> with rev -> {final ProcessGroup group=processGroupDAO.getProcessGroup(groupId); in method public getConnections(groupId String) : Set<ConnectionEntity> from class org.apache.nifi.web.StandardNiFiServiceFacade


    @Override
    public ConfigurationSnapshot<ConnectionDTO> updateConnection(final Revision revision, final String groupId, final ConnectionDTO connectionDTO) {
        // if connection does not exist, then create new connection
        if (connectionDAO.hasConnection(groupId, connectionDTO.getId()) == false) {
            return createConnection(revision, groupId, connectionDTO);
        }

        return updateComponent(revision, () -> connectionDAO.updateConnection(groupId, connectionDTO), connection -> dtoFactory.createConnectionDto(connection));
    }

    @Override
    public ConfigurationSnapshot<ConnectionDTO> updateConnection(final Revision revision, final String groupId, final ConnectionDTO connectionDTO) {
        // if connection does not exist, then create new connection
        if (connectionDAO.hasConnection(groupId, connectionDTO.getId()) == false) {
            return createConnection(revision, groupId, connectionDTO);
        }

        return optimisticLockingManager.configureFlow(revision, new ConfigurationRequest<ConnectionDTO>() {
            @Override
            public ConfigurationResult<ConnectionDTO> execute() {
                final Connection connection = connectionDAO.updateConnection(groupId, connectionDTO);

                controllerFacade.save();

                return new ConfigurationResult<ConnectionDTO>() {
                    @Override
                    public boolean isNew() {
                        return false;
                    }

                    @Override
                    public ConnectionDTO getConfiguration() {
                        return dtoFactory.createConnectionDto(connection);
                    }
                };
            }
        });
    }

Replace Anonymous With Lambda org.apache.nifi.web.StandardNiFiServiceFacade.updateConnection.configureFlow.new ConfigurationRequest<ConnectionDTO> with () -> connectionDAO.updateConnection(groupId,connectionDTO) in method public updateConnection(revision Revision, groupId String, connectionDTO ConnectionDTO) : ConfigurationSnapshot<ConnectionDTO> from class org.apache.nifi.web.StandardNiFiServiceFacade


    @Override
    public ConfigurationSnapshot<ProcessorDTO> updateProcessor(final Revision revision, final String groupId, final ProcessorDTO processorDTO) {
        // if processor does not exist, then create new processor
        if (processorDAO.hasProcessor(groupId, processorDTO.getId()) == false) {
            return createProcessor(revision, groupId, processorDTO);
        }

        return updateComponent(revision, () -> processorDAO.updateProcessor(groupId, processorDTO), proc -> dtoFactory.createProcessorDto(proc));
    }

    @Override
    public ConfigurationSnapshot<ProcessorDTO> updateProcessor(final Revision revision, final String groupId, final ProcessorDTO processorDTO) {
        // if processor does not exist, then create new processor
        if (processorDAO.hasProcessor(groupId, processorDTO.getId()) == false) {
            return createProcessor(revision, groupId, processorDTO);
        }

        return optimisticLockingManager.configureFlow(revision, new ConfigurationRequest<ProcessorDTO>() {
            @Override
            public ConfigurationResult<ProcessorDTO> execute() {
                // update the processor
                final ProcessorNode processor = processorDAO.updateProcessor(groupId, processorDTO);

                // save the flow
                controllerFacade.save();

                return new ConfigurationResult<ProcessorDTO>() {
                    @Override
                    public boolean isNew() {
                        return false;
                    }

                    @Override
                    public ProcessorDTO getConfiguration() {
                        return dtoFactory.createProcessorDto(processor);
                    }
                };
            }
        });
    }

Replace Anonymous With Lambda org.apache.nifi.web.StandardNiFiServiceFacade.updateProcessor.configureFlow.new ConfigurationRequest<ProcessorDTO> with () -> processorDAO.updateProcessor(groupId,processorDTO) in method public updateProcessor(revision Revision, groupId String, processorDTO ProcessorDTO) : ConfigurationSnapshot<ProcessorDTO> from class org.apache.nifi.web.StandardNiFiServiceFacade


    @Override
    public ConfigurationSnapshot<LabelDTO> updateLabel(final Revision revision, final String groupId, final LabelDTO labelDTO) {
        // if label does not exist, then create new label
        if (labelDAO.hasLabel(groupId, labelDTO.getId()) == false) {
            return createLabel(revision, groupId, labelDTO);
        }

        return updateComponent(revision, () -> labelDAO.updateLabel(groupId, labelDTO), label -> dtoFactory.createLabelDto(label));
    }

    @Override
    public ConfigurationSnapshot<LabelDTO> updateLabel(final Revision revision, final String groupId, final LabelDTO labelDTO) {
        // if label does not exist, then create new label
        if (labelDAO.hasLabel(groupId, labelDTO.getId()) == false) {
            return createLabel(revision, groupId, labelDTO);
        }

        return optimisticLockingManager.configureFlow(revision, new ConfigurationRequest<LabelDTO>() {
            @Override
            public ConfigurationResult<LabelDTO> execute() {
                // update the existing label
                final Label label = labelDAO.updateLabel(groupId, labelDTO);

                // save updated controller
                controllerFacade.save();

                return new ConfigurationResult<LabelDTO>() {
                    @Override
                    public boolean isNew() {
                        return false;
                    }

                    @Override
                    public LabelDTO getConfiguration() {
                        return dtoFactory.createLabelDto(label);
                    }
                };
            }
        });
    }

Replace Anonymous With Lambda org.apache.nifi.web.StandardNiFiServiceFacade.updateLabel.configureFlow.new ConfigurationRequest<LabelDTO> with () -> labelDAO.updateLabel(groupId,labelDTO) in method public updateLabel(revision Revision, groupId String, labelDTO LabelDTO) : ConfigurationSnapshot<LabelDTO> from class org.apache.nifi.web.StandardNiFiServiceFacade


    @Override
    public ConfigurationSnapshot<FunnelDTO> updateFunnel(final Revision revision, final String groupId, final FunnelDTO funnelDTO) {
        // if label does not exist, then create new label
        if (funnelDAO.hasFunnel(groupId, funnelDTO.getId()) == false) {
            return createFunnel(revision, groupId, funnelDTO);
        }

        return updateComponent(revision, () -> funnelDAO.updateFunnel(groupId, funnelDTO), funnel -> dtoFactory.createFunnelDto(funnel));
    }

    @Override
    public ConfigurationSnapshot<FunnelDTO> updateFunnel(final Revision revision, final String groupId, final FunnelDTO funnelDTO) {
        // if label does not exist, then create new label
        if (funnelDAO.hasFunnel(groupId, funnelDTO.getId()) == false) {
            return createFunnel(revision, groupId, funnelDTO);
        }

        return optimisticLockingManager.configureFlow(revision, new ConfigurationRequest<FunnelDTO>() {
            @Override
            public ConfigurationResult<FunnelDTO> execute() {
                // update the existing label
                final Funnel funnel = funnelDAO.updateFunnel(groupId, funnelDTO);

                // save updated controller
                controllerFacade.save();

                return new ConfigurationResult<FunnelDTO>() {
                    @Override
                    public boolean isNew() {
                        return false;
                    }

                    @Override
                    public FunnelDTO getConfiguration() {
                        return dtoFactory.createFunnelDto(funnel);
                    }
                };
            }
        });
    }

Replace Anonymous With Lambda org.apache.nifi.web.StandardNiFiServiceFacade.updateFunnel.configureFlow.new ConfigurationRequest<FunnelDTO> with () -> funnelDAO.updateFunnel(groupId,funnelDTO) in method public updateFunnel(revision Revision, groupId String, funnelDTO FunnelDTO) : ConfigurationSnapshot<FunnelDTO> from class org.apache.nifi.web.StandardNiFiServiceFacade


    @Override
    public ConfigurationSnapshot<PortDTO> updateInputPort(final Revision revision, final String groupId, final PortDTO inputPortDTO) {
        // if input port does not exist, then create new input port
        if (inputPortDAO.hasPort(groupId, inputPortDTO.getId()) == false) {
            return createInputPort(revision, groupId, inputPortDTO);
        }

        return updateComponent(revision, () -> inputPortDAO.updatePort(groupId, inputPortDTO), port -> dtoFactory.createPortDto(port));
    }

    @Override
    public ConfigurationSnapshot<PortDTO> updateInputPort(final Revision revision, final String groupId, final PortDTO inputPortDTO) {
        // if input port does not exist, then create new input port
        if (inputPortDAO.hasPort(groupId, inputPortDTO.getId()) == false) {
            return createInputPort(revision, groupId, inputPortDTO);
        }

        return optimisticLockingManager.configureFlow(revision, new ConfigurationRequest<PortDTO>() {
            @Override
            public ConfigurationResult<PortDTO> execute() {
                final Port inputPort = inputPortDAO.updatePort(groupId, inputPortDTO);

                // save updated controller
                controllerFacade.save();

                return new ConfigurationResult<PortDTO>() {
                    @Override
                    public boolean isNew() {
                        return false;
                    }

                    @Override
                    public PortDTO getConfiguration() {
                        return dtoFactory.createPortDto(inputPort);
                    }
                };
            }
        });
    }

Replace Anonymous With Lambda org.apache.nifi.web.StandardNiFiServiceFacade.updateInputPort.configureFlow.new ConfigurationRequest<PortDTO> with () -> inputPortDAO.updatePort(groupId,inputPortDTO) in method public updateInputPort(revision Revision, groupId String, inputPortDTO PortDTO) : ConfigurationSnapshot<PortDTO> from class org.apache.nifi.web.StandardNiFiServiceFacade


    @Override
    public ConfigurationSnapshot<PortDTO> updateOutputPort(final Revision revision, final String groupId, final PortDTO outputPortDTO) {
        // if output port does not exist, then create new output port
        if (outputPortDAO.hasPort(groupId, outputPortDTO.getId()) == false) {
            return createOutputPort(revision, groupId, outputPortDTO);
        }

        return updateComponent(revision, () -> outputPortDAO.updatePort(groupId, outputPortDTO), port -> dtoFactory.createPortDto(port));
    }

    @Override
    public ConfigurationSnapshot<PortDTO> updateOutputPort(final Revision revision, final String groupId, final PortDTO outputPortDTO) {
        // if output port does not exist, then create new output port
        if (outputPortDAO.hasPort(groupId, outputPortDTO.getId()) == false) {
            return createOutputPort(revision, groupId, outputPortDTO);
        }

        return optimisticLockingManager.configureFlow(revision, new ConfigurationRequest<PortDTO>() {
            @Override
            public ConfigurationResult<PortDTO> execute() {
                final Port outputPort = outputPortDAO.updatePort(groupId, outputPortDTO);

                // save updated controller
                controllerFacade.save();

                return new ConfigurationResult<PortDTO>() {
                    @Override
                    public boolean isNew() {
                        return false;
                    }

                    @Override
                    public PortDTO getConfiguration() {
                        return dtoFactory.createPortDto(outputPort);
                    }
                };
            }
        });
    }

Replace Anonymous With Lambda org.apache.nifi.web.StandardNiFiServiceFacade.updateOutputPort.configureFlow.new ConfigurationRequest<PortDTO> with () -> outputPortDAO.updatePort(groupId,outputPortDTO) in method public updateOutputPort(revision Revision, groupId String, outputPortDTO PortDTO) : ConfigurationSnapshot<PortDTO> from class org.apache.nifi.web.StandardNiFiServiceFacade


    @Override
    public ConfigurationSnapshot<ProcessGroupDTO> updateProcessGroup(final Revision revision, final String parentGroupId, final ProcessGroupDTO processGroupDTO) {
        // if process group does not exist, then create new process group
        if (processGroupDAO.hasProcessGroup(processGroupDTO.getId()) == false) {
            if (parentGroupId == null) {
                throw new IllegalArgumentException("Unable to create the specified process group since the parent group was not specified.");
            } else {
                return createProcessGroup(parentGroupId, revision, processGroupDTO);
            }
        }

        return updateComponent(revision, () -> processGroupDAO.updateProcessGroup(processGroupDTO), processGroup -> dtoFactory.createProcessGroupDto(processGroup));
    }

    @Override
    public ConfigurationSnapshot<ProcessGroupDTO> updateProcessGroup(final Revision revision, final String parentGroupId, final ProcessGroupDTO processGroupDTO) {
        // if process group does not exist, then create new process group
        if (processGroupDAO.hasProcessGroup(processGroupDTO.getId()) == false) {
            if (parentGroupId == null) {
                throw new IllegalArgumentException("Unable to create the specified process group since the parent group was not specified.");
            } else {
                return createProcessGroup(parentGroupId, revision, processGroupDTO);
            }
        }

        return optimisticLockingManager.configureFlow(revision, new ConfigurationRequest<ProcessGroupDTO>() {
            @Override
            public ConfigurationResult<ProcessGroupDTO> execute() {
                // update the process group
                final ProcessGroup processGroup = processGroupDAO.updateProcessGroup(processGroupDTO);

                // save updated controller
                controllerFacade.save();

                return new ConfigurationResult<ProcessGroupDTO>() {
                    @Override
                    public boolean isNew() {
                        return false;
                    }

                    @Override
                    public ProcessGroupDTO getConfiguration() {
                        return dtoFactory.createProcessGroupDto(processGroup);
                    }
                };
            }
        });
    }

Replace Anonymous With Lambda org.apache.nifi.web.StandardNiFiServiceFacade.updateProcessGroup.configureFlow.new ConfigurationRequest<ProcessGroupDTO> with () -> processGroupDAO.updateProcessGroup(processGroupDTO) in method public updateProcessGroup(revision Revision, parentGroupId String, processGroupDTO ProcessGroupDTO) : ConfigurationSnapshot<ProcessGroupDTO> from class org.apache.nifi.web.StandardNiFiServiceFacade


    @Override
    public ConfigurationSnapshot<ControllerConfigurationDTO> updateControllerConfiguration(final Revision revision, final ControllerConfigurationDTO controllerConfigurationDTO) {
        return updateComponent(revision,
            () -> {
                // update the controller configuration through the proxy
                if (controllerConfigurationDTO.getName() != null) {
                    controllerFacade.setName(controllerConfigurationDTO.getName());
                }
                if (controllerConfigurationDTO.getComments() != null) {
                    controllerFacade.setComments(controllerConfigurationDTO.getComments());
                }
                if (controllerConfigurationDTO.getMaxTimerDrivenThreadCount() != null) {
                    controllerFacade.setMaxTimerDrivenThreadCount(controllerConfigurationDTO.getMaxTimerDrivenThreadCount());
                }
                if (controllerConfigurationDTO.getMaxEventDrivenThreadCount() != null) {
                    controllerFacade.setMaxEventDrivenThreadCount(controllerConfigurationDTO.getMaxEventDrivenThreadCount());
                }

                return controllerConfigurationDTO;
            },
            controller -> getControllerConfiguration());
    }

    @Override
    public ConfigurationSnapshot<ControllerConfigurationDTO> updateControllerConfiguration(final Revision revision, final ControllerConfigurationDTO controllerConfigurationDTO) {
        return optimisticLockingManager.configureFlow(revision, new ConfigurationRequest<ControllerConfigurationDTO>() {
            @Override
            public ConfigurationResult<ControllerConfigurationDTO> execute() {
                // update the controller configuration through the proxy
                if (controllerConfigurationDTO.getName() != null) {
                    controllerFacade.setName(controllerConfigurationDTO.getName());
                }
                if (controllerConfigurationDTO.getComments() != null) {
                    controllerFacade.setComments(controllerConfigurationDTO.getComments());
                }
                if (controllerConfigurationDTO.getMaxTimerDrivenThreadCount() != null) {
                    controllerFacade.setMaxTimerDrivenThreadCount(controllerConfigurationDTO.getMaxTimerDrivenThreadCount());
                }
                if (controllerConfigurationDTO.getMaxEventDrivenThreadCount() != null) {
                    controllerFacade.setMaxEventDrivenThreadCount(controllerConfigurationDTO.getMaxEventDrivenThreadCount());
                }

                // create the controller configuration dto
                final ControllerConfigurationDTO controllerConfig = getControllerConfiguration();

                // save the flow
                controllerFacade.save();

                return new ConfigurationResult<ControllerConfigurationDTO>() {
                    @Override
                    public boolean isNew() {
                        return false;
                    }

                    @Override
                    public ControllerConfigurationDTO getConfiguration() {
                        return controllerConfig;
                    }
                };
            }
        });
    }

Replace Anonymous With Lambda org.apache.nifi.web.StandardNiFiServiceFacade.updateControllerConfiguration.configureFlow.new ConfigurationRequest<ControllerConfigurationDTO> with () -> {if(controllerConfigurationDTO.getName() != null){controllerFacade.setName(controllerConfigurationDTO.getName()); in method public updateControllerConfiguration(revision Revision, controllerConfigurationDTO ControllerConfigurationDTO) : ConfigurationSnapshot<ControllerConfigurationDTO> from class org.apache.nifi.web.StandardNiFiServiceFacade