org.apache.nifi.nar.NarCloseable Java Examples

The following examples show how to use org.apache.nifi.nar.NarCloseable. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ReportingTaskWrapper.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Override
public synchronized void run() {
    lifecycleState.incrementActiveThreadCount(null);
    try (final NarCloseable narCloseable = NarCloseable.withComponentNarLoader(extensionManager, taskNode.getReportingTask().getClass(), taskNode.getIdentifier())) {
        taskNode.getReportingTask().onTrigger(taskNode.getReportingContext());
    } catch (final Throwable t) {
        final ComponentLog componentLog = new SimpleProcessLogger(taskNode.getIdentifier(), taskNode.getReportingTask());
        componentLog.error("Error running task {} due to {}", new Object[]{taskNode.getReportingTask(), t.toString()});
        if (componentLog.isDebugEnabled()) {
            componentLog.error("", t);
        }
    } finally {
        try {
            // if the reporting task is no longer scheduled to run and this is the last thread,
            // invoke the OnStopped methods
            if (!lifecycleState.isScheduled() && lifecycleState.getActiveThreadCount() == 1 && lifecycleState.mustCallOnStoppedMethods()) {
                try (final NarCloseable x = NarCloseable.withComponentNarLoader(extensionManager, taskNode.getReportingTask().getClass(), taskNode.getIdentifier())) {
                    ReflectionUtils.quietlyInvokeMethodsWithAnnotation(OnStopped.class, taskNode.getReportingTask(), taskNode.getConfigurationContext());
                }
            }
        } finally {
            lifecycleState.decrementActiveThreadCount(null);
        }
    }
}
 
Example #2
Source File: AbstractConfiguredComponent.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
@Override
public Map<PropertyDescriptor, String> getProperties() {
    try (final NarCloseable narCloseable = NarCloseable.withComponentNarLoader(component.getClass(), component.getIdentifier())) {
        final List<PropertyDescriptor> supported = component.getPropertyDescriptors();
        if (supported == null || supported.isEmpty()) {
            return Collections.unmodifiableMap(properties);
        } else {
            final Map<PropertyDescriptor, String> props = new LinkedHashMap<>();
            for (final PropertyDescriptor descriptor : supported) {
                props.put(descriptor, null);
            }
            props.putAll(properties);
            return props;
        }
    }
}
 
Example #3
Source File: FlowController.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Override
public void run() {
    try (final NarCloseable narCloseable = NarCloseable.withFrameworkNar()) {
        if (heartbeatsSuspended.get()) {
            return;
        }

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

        heartbeater.send(message);
    } catch (final UnknownServiceAddressException usae) {
        if (LOG.isDebugEnabled()) {
            LOG.debug(usae.getMessage());
        }
    } catch (final Throwable ex) {
        LOG.warn("Failed to send heartbeat due to: " + ex);
        if (LOG.isDebugEnabled()) {
            LOG.warn("", ex);
        }
    }
}
 
Example #4
Source File: StandardProcessGroup.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
private void shutdown(final ProcessGroup procGroup) {
    for (final ProcessorNode node : procGroup.getProcessors()) {
        try (final NarCloseable x = NarCloseable.withComponentNarLoader(node.getProcessor().getClass(), node.getIdentifier())) {
            final StandardProcessContext processContext = new StandardProcessContext(node, controllerServiceProvider, encryptor, getStateManager(node.getIdentifier()), variableRegistry);
            ReflectionUtils.quietlyInvokeMethodsWithAnnotation(OnShutdown.class, node.getProcessor(), processContext);
        }
    }

    for (final RemoteProcessGroup rpg : procGroup.getRemoteProcessGroups()) {
        rpg.shutdown();
    }

    // Recursively shutdown child groups.
    for (final ProcessGroup group : procGroup.getProcessGroups()) {
        shutdown(group);
    }
}
 
Example #5
Source File: AbstractConfiguredComponent.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
public Collection<ValidationResult> getValidationErrors(final Set<String> serviceIdentifiersNotToValidate) {
    final List<ValidationResult> results = new ArrayList<>();
    lock.lock();
    try {
        final ValidationContext validationContext = validationContextFactory.newValidationContext(
            serviceIdentifiersNotToValidate, getProperties(), getAnnotationData(), getProcessGroupIdentifier(), getIdentifier());

        final Collection<ValidationResult> validationResults;
        try (final NarCloseable narCloseable = NarCloseable.withComponentNarLoader(component.getClass(), component.getIdentifier())) {
            validationResults = component.validate(validationContext);
        }

        for (final ValidationResult result : validationResults) {
            if (!result.isValid()) {
                results.add(result);
            }
        }
    } catch (final Throwable t) {
        results.add(new ValidationResult.Builder().explanation("Failed to run validation due to " + t.toString()).valid(false).build());
    } finally {
        lock.unlock();
    }
    return results;
}
 
Example #6
Source File: StandardProcessScheduler.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
private synchronized void stopConnectable(final Connectable connectable) {
    final ScheduleState state = getScheduleState(requireNonNull(connectable));
    if (!state.isScheduled()) {
        return;
    }

    state.setScheduled(false);
    getSchedulingAgent(connectable).unschedule(connectable, state);

    if (!state.isScheduled() && state.getActiveThreadCount() == 0 && state.mustCallOnStoppedMethods()) {
        final ConnectableProcessContext processContext = new ConnectableProcessContext(connectable, encryptor, getStateManager(connectable.getIdentifier()));
        try (final NarCloseable x = NarCloseable.withComponentNarLoader(connectable.getClass(), connectable.getIdentifier())) {
            ReflectionUtils.quietlyInvokeMethodsWithAnnotation(OnStopped.class, connectable, processContext);
        }
    }
}
 
Example #7
Source File: StandardProcessorNode.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
/**
 * @param relationshipName
 *            name
 * @return the relationship for this nodes processor for the given name or
 *         creates a new relationship for the given name
 */
@Override
public Relationship getRelationship(final String relationshipName) {
    final Relationship specRel = new Relationship.Builder().name(relationshipName).build();
    Relationship returnRel = specRel;

    final Set<Relationship> relationships;
    try (final NarCloseable narCloseable = NarCloseable.withComponentNarLoader(processor.getClass(), processor.getIdentifier())) {
        relationships = processor.getRelationships();
    }

    for (final Relationship rel : relationships) {
        if (rel.equals(specRel)) {
            returnRel = rel;
            break;
        }
    }
    return returnRel;
}
 
Example #8
Source File: StandardProcessorNode.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
public Set<Relationship> getUndefinedRelationships() {
    final Set<Relationship> undefined = new HashSet<>();
    final Set<Relationship> relationships;
    try (final NarCloseable narCloseable = NarCloseable.withComponentNarLoader(processor.getClass(), processor.getIdentifier())) {
        relationships = processor.getRelationships();
    }

    if (relationships == null) {
        return undefined;
    }
    for (final Relationship relation : relationships) {
        final Set<Connection> connectionSet = this.connections.get(relation);
        if (connectionSet == null || connectionSet.isEmpty()) {
            undefined.add(relation);
        }
    }
    return undefined;
}
 
Example #9
Source File: ReportingTaskWrapper.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
@Override
public synchronized void run() {
    scheduleState.incrementActiveThreadCount();
    try (final NarCloseable narCloseable = NarCloseable.withComponentNarLoader(taskNode.getReportingTask().getClass(), taskNode.getIdentifier())) {
        taskNode.getReportingTask().onTrigger(taskNode.getReportingContext());
    } catch (final Throwable t) {
        final ComponentLog componentLog = new SimpleProcessLogger(taskNode.getIdentifier(), taskNode.getReportingTask());
        componentLog.error("Error running task {} due to {}", new Object[]{taskNode.getReportingTask(), t.toString()});
        if (componentLog.isDebugEnabled()) {
            componentLog.error("", t);
        }
    } finally {
        try {
            // if the reporting task is no longer scheduled to run and this is the last thread,
            // invoke the OnStopped methods
            if (!scheduleState.isScheduled() && scheduleState.getActiveThreadCount() == 1 && scheduleState.mustCallOnStoppedMethods()) {
                try (final NarCloseable x = NarCloseable.withComponentNarLoader(taskNode.getReportingTask().getClass(), taskNode.getIdentifier())) {
                    ReflectionUtils.quietlyInvokeMethodsWithAnnotation(OnStopped.class, taskNode.getReportingTask(), taskNode.getConfigurationContext());
                }
            }
        } finally {
            scheduleState.decrementActiveThreadCount();
        }
    }
}
 
Example #10
Source File: FlowController.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
private void notifyComponentsConfigurationRestored() {
    for (final ProcessorNode procNode : getGroup(getRootGroupId()).findAllProcessors()) {
        final Processor processor = procNode.getProcessor();
        try (final NarCloseable nc = NarCloseable.withComponentNarLoader(processor.getClass(), processor.getIdentifier())) {
            ReflectionUtils.quietlyInvokeMethodsWithAnnotation(OnConfigurationRestored.class, processor);
        }
    }

    for (final ControllerServiceNode serviceNode : getAllControllerServices()) {
        final ControllerService service = serviceNode.getControllerServiceImplementation();

        try (final NarCloseable nc = NarCloseable.withComponentNarLoader(service.getClass(), service.getIdentifier())) {
            ReflectionUtils.quietlyInvokeMethodsWithAnnotation(OnConfigurationRestored.class, service);
        }
    }

    for (final ReportingTaskNode taskNode : getAllReportingTasks()) {
        final ReportingTask task = taskNode.getReportingTask();

        try (final NarCloseable nc = NarCloseable.withComponentNarLoader(task.getClass(), task.getIdentifier())) {
            ReflectionUtils.quietlyInvokeMethodsWithAnnotation(OnConfigurationRestored.class, task);
        }
    }
}
 
Example #11
Source File: FlowController.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
@Override
public void run() {
    try (final NarCloseable narCloseable = NarCloseable.withFrameworkNar()) {
        if (heartbeatsSuspended.get()) {
            return;
        }

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

        heartbeater.send(message);
    } catch (final UnknownServiceAddressException usae) {
        if (LOG.isDebugEnabled()) {
            LOG.debug(usae.getMessage());
        }
    } catch (final Throwable ex) {
        LOG.warn("Failed to send heartbeat due to: " + ex);
        if (LOG.isDebugEnabled()) {
            LOG.warn("", ex);
        }
    }
}
 
Example #12
Source File: TestStandardProcessorNode.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Test
public void testPropertyModifiesClasspathWhenProcessorMissingAnnotation() throws MalformedURLException {
    final MockReloadComponent reloadComponent = new MockReloadComponent();
    final ModifiesClasspathNoAnnotationProcessor processor = new ModifiesClasspathNoAnnotationProcessor();
    final StandardProcessorNode procNode = createProcessorNode(processor, reloadComponent);

    try (final NarCloseable narCloseable = NarCloseable.withComponentNarLoader(extensionManager, procNode.getProcessor().getClass(), procNode.getIdentifier())){

        final Map<String, String> properties = new HashMap<>();
        properties.put(ModifiesClasspathNoAnnotationProcessor.CLASSPATH_RESOURCE.getName(),
                "src/test/resources/TestClasspathResources/resource1.txt");
        procNode.setProperties(properties);

        final URL[] testResources = getTestResources();
        assertTrue(containsResource(reloadComponent.getAdditionalUrls(), testResources[0]));
        assertFalse(containsResource(reloadComponent.getAdditionalUrls(), testResources[1]));
        assertFalse(containsResource(reloadComponent.getAdditionalUrls(), testResources[2]));

        assertEquals(ModifiesClasspathNoAnnotationProcessor.class.getCanonicalName(), reloadComponent.getNewType());

        // Should pass validation
        assertTrue(procNode.computeValidationErrors(procNode.getValidationContext()).isEmpty());
    } finally {
        extensionManager.removeInstanceClassLoader(procNode.getIdentifier());
    }
}
 
Example #13
Source File: StandardProcessorNode.java    From nifi with Apache License 2.0 6 votes vote down vote up
public Set<Relationship> getUndefinedRelationships() {
    final Set<Relationship> undefined = new HashSet<>();
    final Set<Relationship> relationships;
    final Processor processor = processorRef.get().getProcessor();
    try (final NarCloseable narCloseable = NarCloseable.withComponentNarLoader(getExtensionManager(), processor.getClass(), processor.getIdentifier())) {
        relationships = processor.getRelationships();
    }

    if (relationships == null) {
        return undefined;
    }
    for (final Relationship relation : relationships) {
        final Set<Connection> connectionSet = this.connections.get(relation);
        if (connectionSet == null || connectionSet.isEmpty()) {
            undefined.add(relation);
        }
    }
    return undefined;
}
 
Example #14
Source File: StandardProcessorNode.java    From nifi with Apache License 2.0 6 votes vote down vote up
/**
 * @param relationshipName
 *            name
 * @return the relationship for this nodes processor for the given name or
 *         creates a new relationship for the given name
 */
@Override
public Relationship getRelationship(final String relationshipName) {
    final Relationship specRel = new Relationship.Builder().name(relationshipName).build();
    Relationship returnRel = specRel;

    final Set<Relationship> relationships;
    final Processor processor = processorRef.get().getProcessor();
    try (final NarCloseable narCloseable = NarCloseable.withComponentNarLoader(getExtensionManager(), processor.getClass(), processor.getIdentifier())) {
        relationships = processor.getRelationships();
    }

    for (final Relationship rel : relationships) {
        if (rel.equals(specRel)) {
            returnRel = rel;
            break;
        }
    }
    return returnRel;
}
 
Example #15
Source File: FlowController.java    From nifi with Apache License 2.0 6 votes vote down vote up
private void notifyComponentsConfigurationRestored() {
    for (final ProcessorNode procNode : flowManager.getRootGroup().findAllProcessors()) {
        final Processor processor = procNode.getProcessor();
        try (final NarCloseable nc = NarCloseable.withComponentNarLoader(extensionManager, processor.getClass(), processor.getIdentifier())) {
            ReflectionUtils.quietlyInvokeMethodsWithAnnotation(OnConfigurationRestored.class, processor);
        }
    }

    for (final ControllerServiceNode serviceNode : flowManager.getAllControllerServices()) {
        final ControllerService service = serviceNode.getControllerServiceImplementation();

        try (final NarCloseable nc = NarCloseable.withComponentNarLoader(extensionManager, service.getClass(), service.getIdentifier())) {
            ReflectionUtils.quietlyInvokeMethodsWithAnnotation(OnConfigurationRestored.class, service);
        }
    }

    for (final ReportingTaskNode taskNode : getAllReportingTasks()) {
        final ReportingTask task = taskNode.getReportingTask();

        try (final NarCloseable nc = NarCloseable.withComponentNarLoader(extensionManager, task.getClass(), task.getIdentifier())) {
            ReflectionUtils.quietlyInvokeMethodsWithAnnotation(OnConfigurationRestored.class, task);
        }
    }
}
 
Example #16
Source File: AuthorizerInvocationHandler.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Override
public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
    try (final NarCloseable narCloseable = NarCloseable.withComponentNarLoader(classLoader)) {
        if (getAccessPolicyProviderMethod.equals(method)) {
            final AccessPolicyProvider accessPolicyProvider = (AccessPolicyProvider) method.invoke(authorizer, args);
            if (accessPolicyProvider == null) {
                return accessPolicyProvider;
            } else {
                return AccessPolicyProviderFactory.withNarLoader(accessPolicyProvider, classLoader);
            }
        } else {
            return method.invoke(authorizer, args);
        }
    } catch (final InvocationTargetException e) {
        // If the proxied instance throws an Exception, it'll be wrapped in an InvocationTargetException. We want
        // to instead re-throw what the proxied instance threw, so we pull it out of the InvocationTargetException.
        throw e.getCause();
    }
}
 
Example #17
Source File: AccessPolicyProviderInvocationHandler.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Override
public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
    try (final NarCloseable narCloseable = NarCloseable.withComponentNarLoader(classLoader)) {
        if (getUserGroupProviderMethod.equals(method)) {
            final UserGroupProvider userGroupProvider = (UserGroupProvider) method.invoke(accessPolicyProvider, args);
            if (userGroupProvider == null) {
                return userGroupProvider;
            } else {
                return UserGroupProviderFactory.withNarLoader(userGroupProvider, classLoader);
            }
        } else {
            return method.invoke(accessPolicyProvider, args);
        }
    } catch (final InvocationTargetException e) {
        // If the proxied instance throws an Exception, it'll be wrapped in an InvocationTargetException. We want
        // to instead re-throw what the proxied instance threw, so we pull it out of the InvocationTargetException.
        throw e.getCause();
    }
}
 
Example #18
Source File: SearchableMatcher.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Override
public void match(final ProcessorNode component, final SearchQuery query, final List<String> matches) {
    final Processor processor = component.getProcessor();

    if (processor instanceof Searchable) {
        final Searchable searchable = (Searchable) processor;
        final String searchTerm = query.getTerm();
        final SearchContext context = new StandardSearchContext(searchTerm, component, flowController.getControllerServiceProvider(), variableRegistry);

        // search the processor using the appropriate thread context classloader
        try (final NarCloseable narCloseable = NarCloseable.withComponentNarLoader(flowController.getExtensionManager(), component.getClass(), component.getIdentifier())) {
            searchable.search(context).stream().forEach(searchResult -> matches.add(searchResult.getLabel() + AttributeMatcher.SEPARATOR + searchResult.getMatch()));
        } catch (final Throwable t) {
            LOGGER.error("Error happened during searchable matching: {}", t.getMessage());
            t.printStackTrace();
        }
    }
}
 
Example #19
Source File: AbstractComponentNode.java    From nifi with Apache License 2.0 6 votes vote down vote up
public Map<PropertyDescriptor, PropertyConfiguration> getProperties() {
    try (final NarCloseable narCloseable = NarCloseable.withComponentNarLoader(extensionManager, getComponent().getClass(), getIdentifier())) {
        final List<PropertyDescriptor> supported = getComponent().getPropertyDescriptors();
        if (supported == null || supported.isEmpty()) {
            return Collections.unmodifiableMap(properties);
        } else {
            final Map<PropertyDescriptor, PropertyConfiguration> props = new LinkedHashMap<>();

            for (final PropertyDescriptor descriptor : supported) {
                props.put(descriptor, null);
            }

            props.putAll(properties);
            return props;
        }
    }
}
 
Example #20
Source File: FlowController.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
@Override
public ControllerServiceNode createControllerService(final String type, final String id, final boolean firstTimeAdded) {
    final ControllerServiceNode serviceNode = controllerServiceProvider.createControllerService(type, id, firstTimeAdded);

    // Register log observer to provide bulletins when reporting task logs anything at WARN level or above
    final LogRepository logRepository = LogRepositoryFactory.getRepository(id);
    logRepository.addObserver(StandardProcessorNode.BULLETIN_OBSERVER_ID, LogLevel.WARN,
            new ControllerServiceLogObserver(getBulletinRepository(), serviceNode));

    if (firstTimeAdded) {
        final ControllerService service = serviceNode.getControllerServiceImplementation();

        try (final NarCloseable nc = NarCloseable.withComponentNarLoader(service.getClass(), service.getIdentifier())) {
            ReflectionUtils.quietlyInvokeMethodsWithAnnotation(OnConfigurationRestored.class, service);
        }
    }

    return serviceNode;
}
 
Example #21
Source File: ControllerServiceInitializer.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
@Override
public void teardown(ConfigurableComponent component) {
    try (NarCloseable narCloseable = NarCloseable.withComponentNarLoader(component.getClass(), component.getIdentifier())) {
        ControllerService controllerService = (ControllerService) component;

        final ComponentLog logger = new MockComponentLogger();
        final MockConfigurationContext context = new MockConfigurationContext();
        ReflectionUtils.quietlyInvokeMethodsWithAnnotation(OnShutdown.class, controllerService, logger, context);
    } finally {
        ExtensionManager.removeInstanceClassLoaderIfExists(component.getIdentifier());
    }
}
 
Example #22
Source File: FlowController.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
public void setPrimary(final boolean primary) {
    final PrimaryNodeState nodeState = primary ? PrimaryNodeState.ELECTED_PRIMARY_NODE : PrimaryNodeState.PRIMARY_NODE_REVOKED;
    final ProcessGroup rootGroup = getGroup(getRootGroupId());
    for (final ProcessorNode procNode : rootGroup.findAllProcessors()) {
        try (final NarCloseable narCloseable = NarCloseable.withComponentNarLoader(procNode.getProcessor().getClass(), procNode.getIdentifier())) {
            ReflectionUtils.quietlyInvokeMethodsWithAnnotation(OnPrimaryNodeStateChange.class, procNode.getProcessor(), nodeState);
        }
    }
    for (final ControllerServiceNode serviceNode : getAllControllerServices()) {
        try (final NarCloseable narCloseable = NarCloseable.withComponentNarLoader(serviceNode.getControllerServiceImplementation().getClass(), serviceNode.getIdentifier())) {
            ReflectionUtils.quietlyInvokeMethodsWithAnnotation(OnPrimaryNodeStateChange.class, serviceNode.getControllerServiceImplementation(), nodeState);
        }
    }
    for (final ReportingTaskNode reportingTaskNode : getAllReportingTasks()) {
        try (final NarCloseable narCloseable = NarCloseable.withComponentNarLoader(reportingTaskNode.getReportingTask().getClass(), reportingTaskNode.getIdentifier())) {
            ReflectionUtils.quietlyInvokeMethodsWithAnnotation(OnPrimaryNodeStateChange.class, reportingTaskNode.getReportingTask(), nodeState);
        }
    }

    // update primary
    eventDrivenWorkerQueue.setPrimary(primary);

    // update the heartbeat bean
    final HeartbeatBean oldBean = this.heartbeatBeanRef.getAndSet(new HeartbeatBean(rootGroup, primary));

    // Emit a bulletin detailing the fact that the primary node state has changed
    if (oldBean == null || oldBean.isPrimary() != primary) {
        final String message = primary ? "This node has been elected Primary Node" : "This node is no longer Primary Node";
        final Bulletin bulletin = BulletinFactory.createBulletin("Primary Node", Severity.INFO.name(), message);
        bulletinRepository.addBulletin(bulletin);
        LOG.info(message);
    }
}
 
Example #23
Source File: TestStandardProcessorNode.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
@Test
public void testPropertyModifiesClasspathWhenProcessorMissingAnnotation() throws MalformedURLException {
    final ModifiesClasspathNoAnnotationProcessor processor = new ModifiesClasspathNoAnnotationProcessor();
    final StandardProcessorNode procNode = createProcessorNode(processor);

    final Set<ClassLoader> classLoaders = new HashSet<>();
    classLoaders.add(procNode.getProcessor().getClass().getClassLoader());

    // Load all of the extensions in src/test/java of this project
    ExtensionManager.discoverExtensions(classLoaders);

    try (final NarCloseable narCloseable = NarCloseable.withComponentNarLoader(procNode.getProcessor().getClass(), procNode.getIdentifier())){
        // Can't validate the ClassLoader here b/c the class is missing the annotation

        // Simulate setting the properties pointing to two of the resources
        final Map<String, String> properties = new HashMap<>();
        properties.put(ModifiesClasspathNoAnnotationProcessor.CLASSPATH_RESOURCE.getName(),
                "src/test/resources/TestClasspathResources/resource1.txt");
        procNode.setProperties(properties);

        // Should not have loaded any of the resources
        final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        assertTrue(classLoader instanceof URLClassLoader);

        final URL[] testResources = getTestResources();
        final URLClassLoader urlClassLoader = (URLClassLoader) classLoader;
        assertFalse(containsResource(urlClassLoader.getURLs(), testResources[0]));
        assertFalse(containsResource(urlClassLoader.getURLs(), testResources[1]));
        assertFalse(containsResource(urlClassLoader.getURLs(), testResources[2]));

        // Should pass validation
        assertTrue(procNode.isValid());

    } finally {
        ExtensionManager.removeInstanceClassLoaderIfExists(procNode.getIdentifier());
    }
}
 
Example #24
Source File: ControllerServiceInitializer.java    From nifi-minifi with Apache License 2.0 5 votes vote down vote up
@Override
public void initialize(ConfigurableComponent component) throws InitializationException {
    ControllerService controllerService = (ControllerService) component;
    ControllerServiceInitializationContext context = new MockControllerServiceInitializationContext();
    try (NarCloseable narCloseable = NarCloseable.withComponentNarLoader(component.getClass(), context.getIdentifier())) {
        controllerService.initialize(context);
    }
}
 
Example #25
Source File: ControllerServiceInitializer.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Override
public void teardown(ConfigurableComponent component) {
    try (NarCloseable narCloseable = NarCloseable.withComponentNarLoader(extensionManager, component.getClass(), component.getIdentifier())) {
        ControllerService controllerService = (ControllerService) component;

        final ComponentLog logger = new MockComponentLogger();
        final MockConfigurationContext context = new MockConfigurationContext();
        ReflectionUtils.quietlyInvokeMethodsWithAnnotation(OnShutdown.class, controllerService, logger, context);
    } finally {
        extensionManager.removeInstanceClassLoader(component.getIdentifier());
    }
}
 
Example #26
Source File: ProcessorInitializer.java    From nifi-minifi with Apache License 2.0 5 votes vote down vote up
@Override
public void initialize(ConfigurableComponent component) {
    Processor processor = (Processor) component;
    ProcessorInitializationContext initializationContext = new MockProcessorInitializationContext();
    try (NarCloseable narCloseable = NarCloseable.withComponentNarLoader(component.getClass(), initializationContext.getIdentifier())) {
        processor.initialize(initializationContext);
    }
}
 
Example #27
Source File: ProcessorInitializer.java    From nifi-minifi with Apache License 2.0 5 votes vote down vote up
@Override
public void teardown(ConfigurableComponent component) {
    Processor processor = (Processor) component;
    try (NarCloseable narCloseable = NarCloseable.withComponentNarLoader(component.getClass(), component.getIdentifier())) {

        final ComponentLog logger = new MockComponentLogger();
        final MockProcessContext context = new MockProcessContext();
        ReflectionUtils.quietlyInvokeMethodsWithAnnotation(OnShutdown.class, processor, logger, context);
    } finally {
        ExtensionManager.removeInstanceClassLoader(component.getIdentifier());
    }
}
 
Example #28
Source File: ReportingTaskingInitializer.java    From nifi-minifi with Apache License 2.0 5 votes vote down vote up
@Override
public void initialize(ConfigurableComponent component) throws InitializationException {
    ReportingTask reportingTask = (ReportingTask) component;
    ReportingInitializationContext context = new MockReportingInitializationContext();
    try (NarCloseable narCloseable = NarCloseable.withComponentNarLoader(component.getClass(), context.getIdentifier())) {
        reportingTask.initialize(context);
    }
}
 
Example #29
Source File: FlowController.java    From nifi with Apache License 2.0 5 votes vote down vote up
public void setPrimary(final boolean primary) {
    final PrimaryNodeState nodeState = primary ? PrimaryNodeState.ELECTED_PRIMARY_NODE : PrimaryNodeState.PRIMARY_NODE_REVOKED;
    final ProcessGroup rootGroup = flowManager.getRootGroup();
    for (final ProcessorNode procNode : rootGroup.findAllProcessors()) {
        try (final NarCloseable narCloseable = NarCloseable.withComponentNarLoader(extensionManager, procNode.getProcessor().getClass(), procNode.getIdentifier())) {
            ReflectionUtils.quietlyInvokeMethodsWithAnnotation(OnPrimaryNodeStateChange.class, procNode.getProcessor(), nodeState);
        }
    }
    for (final ControllerServiceNode serviceNode : flowManager.getAllControllerServices()) {
        final Class<?> serviceImplClass = serviceNode.getControllerServiceImplementation().getClass();
        try (final NarCloseable narCloseable = NarCloseable.withComponentNarLoader(extensionManager, serviceImplClass, serviceNode.getIdentifier())) {
            ReflectionUtils.quietlyInvokeMethodsWithAnnotation(OnPrimaryNodeStateChange.class, serviceNode.getControllerServiceImplementation(), nodeState);
        }
    }
    for (final ReportingTaskNode reportingTaskNode : getAllReportingTasks()) {
        try (final NarCloseable narCloseable = NarCloseable.withComponentNarLoader(extensionManager, reportingTaskNode.getReportingTask().getClass(), reportingTaskNode.getIdentifier())) {
            ReflectionUtils.quietlyInvokeMethodsWithAnnotation(OnPrimaryNodeStateChange.class, reportingTaskNode.getReportingTask(), nodeState);
        }
    }

    // update primary
    eventDrivenWorkerQueue.setPrimary(primary);

    // update the heartbeat bean
    final HeartbeatBean oldBean = this.heartbeatBeanRef.getAndSet(new HeartbeatBean(rootGroup, primary));

    // Emit a bulletin detailing the fact that the primary node state has changed
    if (oldBean == null || oldBean.isPrimary() != primary) {
        final String message = primary ? "This node has been elected Primary Node" : "This node is no longer Primary Node";
        final Bulletin bulletin = BulletinFactory.createBulletin("Primary Node", Severity.INFO.name(), message);
        bulletinRepository.addBulletin(bulletin);
        LOG.info(message);
    }
}
 
Example #30
Source File: ReportingTaskingInitializer.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Override
public void teardown(ConfigurableComponent component) {
    ReportingTask reportingTask = (ReportingTask) component;
    try (NarCloseable narCloseable = NarCloseable.withComponentNarLoader(extensionManager, component.getClass(), component.getIdentifier())) {

        final MockConfigurationContext context = new MockConfigurationContext();
        ReflectionUtils.quietlyInvokeMethodsWithAnnotation(OnShutdown.class, reportingTask, new MockComponentLogger(), context);
    } finally {
        extensionManager.removeInstanceClassLoader(component.getIdentifier());
    }
}