Java Code Examples for org.apache.nifi.components.state.StateManager

The following examples show how to use org.apache.nifi.components.state.StateManager. These examples are extracted from open source projects. 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
@Override
public void assertNotValid(final ControllerService service) {
    final StateManager serviceStateManager = controllerServiceStateManagers.get(service.getIdentifier());
    if (serviceStateManager == null) {
        throw new IllegalStateException("Controller Service has not been added to this TestRunner via the #addControllerService method");
    }

    final ValidationContext validationContext = new MockValidationContext(context, serviceStateManager, variableRegistry).getControllerServiceValidationContext(service);
    final Collection<ValidationResult> results = context.getControllerService(service.getIdentifier()).validate(validationContext);

    for (final ValidationResult result : results) {
        if (!result.isValid()) {
            return;
        }
    }

    Assert.fail("Expected Controller Service " + service + " to be invalid but it is valid");
}
 
Example 2
Source Project: localization_nifi   Source File: GetSplunk.java    License: Apache License 2.0 6 votes vote down vote up
private TimeRange loadState(StateManager stateManager) throws IOException {
    final StateMap stateMap = stateManager.getState(Scope.CLUSTER);

    if (stateMap.getVersion() < 0) {
        getLogger().debug("No previous state found");
        return null;
    }

    final String earliest = stateMap.get(EARLIEST_TIME_KEY);
    final String latest = stateMap.get(LATEST_TIME_KEY);
    getLogger().debug("Loaded state with earliestTime of {} and latestTime of {}", new Object[] {earliest, latest});

    if (StringUtils.isBlank(earliest) && StringUtils.isBlank(latest)) {
        return null;
    } else {
        return new TimeRange(earliest, latest);
    }
}
 
Example 3
private ProcessorNode createProcessor(final StandardProcessScheduler scheduler, final ControllerServiceProvider serviceProvider) {
    final ReloadComponent reloadComponent = Mockito.mock(ReloadComponent.class);

    final Processor processor = new DummyProcessor();
    final MockProcessContext context = new MockProcessContext(processor, Mockito.mock(StateManager.class), variableRegistry);
    final MockProcessorInitializationContext mockInitContext = new MockProcessorInitializationContext(processor, context);
    processor.initialize(mockInitContext);

    final LoggableComponent<Processor> dummyProcessor = new LoggableComponent<>(processor, systemBundle.getBundleDetails().getCoordinate(), null);
    final ProcessorNode procNode = new StandardProcessorNode(dummyProcessor, mockInitContext.getIdentifier(),
            new StandardValidationContextFactory(serviceProvider, null), scheduler, serviceProvider,
            new StandardComponentVariableRegistry(VariableRegistry.EMPTY_REGISTRY), reloadComponent, extensionManager, new SynchronousValidationTrigger());

    final FlowManager flowManager = Mockito.mock(FlowManager.class);
    final FlowController flowController = Mockito.mock(FlowController.class );
    Mockito.when(flowController.getFlowManager()).thenReturn(flowManager);

    final ProcessGroup group = new StandardProcessGroup(UUID.randomUUID().toString(), serviceProvider, scheduler, null, null, flowController,
        new MutableVariableRegistry(variableRegistry));
    group.addProcessor(procNode);
    procNode.setProcessGroup(group);

    return procNode;
}
 
Example 4
Source Project: nifi   Source File: GetSplunk.java    License: Apache License 2.0 6 votes vote down vote up
private TimeRange loadState(StateManager stateManager) throws IOException {
    final StateMap stateMap = stateManager.getState(Scope.CLUSTER);

    if (stateMap.getVersion() < 0) {
        getLogger().debug("No previous state found");
        return null;
    }

    final String earliest = stateMap.get(EARLIEST_TIME_KEY);
    final String latest = stateMap.get(LATEST_TIME_KEY);
    getLogger().debug("Loaded state with earliestTime of {} and latestTime of {}", new Object[] {earliest, latest});

    if (StringUtils.isBlank(earliest) && StringUtils.isBlank(latest)) {
        return null;
    } else {
        return new TimeRange(earliest, latest);
    }
}
 
Example 5
Source Project: nifi   Source File: StandardProcessContext.java    License: Apache License 2.0 6 votes vote down vote up
public StandardProcessContext(final ProcessorNode processorNode, final ControllerServiceProvider controllerServiceProvider, final StringEncryptor encryptor, final StateManager stateManager,
                              final TaskTermination taskTermination) {
    this.procNode = processorNode;
    this.controllerServiceProvider = controllerServiceProvider;
    this.encryptor = encryptor;
    this.stateManager = stateManager;
    this.taskTermination = taskTermination;

    properties = Collections.unmodifiableMap(processorNode.getEffectivePropertyValues());

    preparedQueries = new HashMap<>();
    for (final Map.Entry<PropertyDescriptor, String> entry : processorNode.getRawPropertyValues().entrySet()) {
        final PropertyDescriptor desc = entry.getKey();
        String value = entry.getValue();
        if (value == null) {
            value = desc.getDefaultValue();
        }

        if (value != null) {
            final PreparedQuery pq = Query.prepare(value);
            preparedQueries.put(desc, pq);
        }
    }
}
 
Example 6
Source Project: nifi   Source File: TestPrometheusRecordSink.java    License: Apache License 2.0 6 votes vote down vote up
private PrometheusRecordSink initTask() throws InitializationException {

        final ComponentLog logger = mock(ComponentLog.class);
        final PrometheusRecordSink task = new PrometheusRecordSink();
        ConfigurationContext context = mock(ConfigurationContext.class);
        final StateManager stateManager = new MockStateManager(task);

        final PropertyValue pValue = mock(StandardPropertyValue.class);
        when(context.getProperty(PrometheusMetricsUtil.METRICS_ENDPOINT_PORT)).thenReturn(new MockPropertyValue(portString));
        when(context.getProperty(PrometheusRecordSink.SSL_CONTEXT)).thenReturn(pValue);
        when(pValue.asControllerService(SSLContextService.class)).thenReturn(null);

        final ControllerServiceInitializationContext initContext = new MockControllerServiceInitializationContext(task, UUID.randomUUID().toString(), logger, stateManager);
        task.initialize(initContext);
        task.onScheduled(context);

        return task;
    }
 
Example 7
Source Project: nifi   Source File: AttributeRollingWindow.java    License: Apache License 2.0 6 votes vote down vote up
@OnScheduled
public void onScheduled(final ProcessContext context) throws IOException {
    timeWindow = context.getProperty(TIME_WINDOW).asTimePeriod(TimeUnit.MILLISECONDS);
    microBatchTime = context.getProperty(SUB_WINDOW_LENGTH).asTimePeriod(TimeUnit.MILLISECONDS);

    if(microBatchTime == null || microBatchTime == 0) {
        StateManager stateManager = context.getStateManager();
        StateMap state = stateManager.getState(SCOPE);
        HashMap<String, String> tempMap = new HashMap<>();
        tempMap.putAll(state.toMap());
        if (!tempMap.containsKey(COUNT_KEY)) {
            tempMap.put(COUNT_KEY, "0");
            context.getStateManager().setState(tempMap, SCOPE);
        }
    }
}
 
Example 8
Source Project: localization_nifi   Source File: StandardProcessContext.java    License: Apache License 2.0 6 votes vote down vote up
public StandardProcessContext(final ProcessorNode processorNode, final ControllerServiceProvider controllerServiceProvider, final StringEncryptor encryptor, final StateManager stateManager,
                              final VariableRegistry variableRegistry) {
    this.procNode = processorNode;
    this.controllerServiceProvider = controllerServiceProvider;
    this.encryptor = encryptor;
    this.stateManager = stateManager;
    this.variableRegistry = variableRegistry;

    preparedQueries = new HashMap<>();
    for (final Map.Entry<PropertyDescriptor, String> entry : procNode.getProperties().entrySet()) {
        final PropertyDescriptor desc = entry.getKey();
        String value = entry.getValue();
        if (value == null) {
            value = desc.getDefaultValue();
        }

        if (value != null) {
            final PreparedQuery pq = Query.prepare(value);
            preparedQueries.put(desc, pq);
        }
    }
}
 
Example 9
Source Project: nifi-scripting-samples   Source File: TestState.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Demonstrates reading and writing processor state values
 * @throws Exception
 */
@Test
public void testStateJavascript() throws Exception {
    final TestRunner runner = TestRunners.newTestRunner(new ExecuteScript());
    runner.setValidateExpressionUsage(false);
    runner.setProperty(SCRIPT_ENGINE, "ECMAScript");
    runner.setProperty(ScriptingComponentUtils.SCRIPT_FILE, "src/test/resources/executescript/state/state.js");
    runner.setProperty(ScriptingComponentUtils.MODULES, "src/test/resources/executescript");
    runner.assertValid();

    StateManager stateManager = runner.getStateManager();
    stateManager.clear(Scope.CLUSTER);
    Map<String, String> initialStateValues = new HashMap<>();
    initialStateValues.put("some-state", "foo");
    stateManager.setState(initialStateValues, Scope.CLUSTER);

    runner.enqueue("sample text".getBytes(StandardCharsets.UTF_8));
    runner.run();

    runner.assertAllFlowFilesTransferred("success", 1);
    StateMap resultStateValues = stateManager.getState(Scope.CLUSTER);
    Assert.assertEquals("foobar", resultStateValues.get("some-state"));
}
 
Example 10
Source Project: nifi-scripting-samples   Source File: TestState.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Demonstrates reading and writing processor state values
 * @throws Exception
 */
@Test
public void testStatePython() throws Exception {
    final TestRunner runner = TestRunners.newTestRunner(new ExecuteScript());
    runner.setValidateExpressionUsage(false);
    runner.setProperty(SCRIPT_ENGINE, "python");
    runner.setProperty(ScriptingComponentUtils.SCRIPT_FILE, "src/test/resources/executescript/state/state.py");
    runner.setProperty(ScriptingComponentUtils.MODULES, "src/test/resources/executescript");
    runner.assertValid();

    StateManager stateManager = runner.getStateManager();
    stateManager.clear(Scope.CLUSTER);
    Map<String, String> initialStateValues = new HashMap<>();
    initialStateValues.put("some-state", "foo");
    stateManager.setState(initialStateValues, Scope.CLUSTER);

    runner.enqueue("sample text".getBytes(StandardCharsets.UTF_8));
    runner.run();

    runner.assertAllFlowFilesTransferred("success", 1);
    StateMap resultStateValues = stateManager.getState(Scope.CLUSTER);
    Assert.assertEquals("foobar", resultStateValues.get("some-state"));
}
 
Example 11
Source Project: nifi   Source File: ProvenanceEventConsumer.java    License: Apache License 2.0 6 votes vote down vote up
private long updateLastEventId(final List<ProvenanceEventRecord> events, final StateManager stateManager) {
    if (events == null || events.isEmpty()) {
        return firstEventId;
    }

    // Store the id of the last event so we know where we left off
    final ProvenanceEventRecord lastEvent = events.get(events.size() - 1);
    final String lastEventId = String.valueOf(lastEvent.getEventId());
    try {
        Map<String, String> newMapOfState = new HashMap<>();
        newMapOfState.put(LAST_EVENT_ID_KEY, lastEventId);
        stateManager.setState(newMapOfState, Scope.LOCAL);
    } catch (final IOException ioe) {
        logger.error("Failed to update state to {} due to {}; this could result in events being re-sent after a restart. The message of {} was: {}",
                new Object[]{lastEventId, ioe, ioe, ioe.getMessage()}, ioe);
    }

    return lastEvent.getEventId() + 1;
}
 
Example 12
Source Project: nifi   Source File: StandardProcessorTestRunner.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void assertNotValid(final ControllerService service) {
    final StateManager serviceStateManager = controllerServiceStateManagers.get(service.getIdentifier());
    if (serviceStateManager == null) {
        throw new IllegalStateException("Controller Service has not been added to this TestRunner via the #addControllerService method");
    }

    final ValidationContext validationContext = new MockValidationContext(context, serviceStateManager, variableRegistry).getControllerServiceValidationContext(service);
    final Collection<ValidationResult> results = context.getControllerService(service.getIdentifier()).validate(validationContext);

    for (final ValidationResult result : results) {
        if (!result.isValid()) {
            return;
        }
    }

    Assert.fail("Expected Controller Service " + service + " to be invalid but it is valid");
}
 
Example 13
Source Project: nifi   Source File: StandardProcessorTestRunner.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void assertValid(final ControllerService service) {
    final StateManager serviceStateManager = controllerServiceStateManagers.get(service.getIdentifier());
    if (serviceStateManager == null) {
        throw new IllegalStateException("Controller Service has not been added to this TestRunner via the #addControllerService method");
    }

    final ValidationContext validationContext = new MockValidationContext(context, serviceStateManager, variableRegistry).getControllerServiceValidationContext(service);
    final Collection<ValidationResult> results = context.getControllerService(service.getIdentifier()).validate(validationContext);

    for (final ValidationResult result : results) {
        if (!result.isValid()) {
            Assert.fail("Expected Controller Service to be valid but it is invalid due to: " + result.toString());
        }
    }
}
 
Example 14
Source Project: nifi   Source File: QueryDatabaseTableRecordTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testGetQueryUsingPhoenixAdapter() throws Exception {
    Map<String, String> maxValues = new HashMap<>();
    StateManager stateManager = runner.getStateManager();
    processor.putColumnType("mytable" + AbstractDatabaseFetchProcessor.NAMESPACE_DELIMITER + "id", Types.INTEGER);
    processor.putColumnType("mytable" + AbstractDatabaseFetchProcessor.NAMESPACE_DELIMITER + "time_created", Types.TIME);
    processor.putColumnType("mytable" + AbstractDatabaseFetchProcessor.NAMESPACE_DELIMITER + "date_created", Types.TIMESTAMP);

    maxValues.put("id", "509");
    maxValues.put("time_created", "12:34:57");
    maxValues.put("date_created", "2016-03-07 12:34:56");
    stateManager.setState(maxValues, Scope.CLUSTER);

    dbAdapter = new PhoenixDatabaseAdapter();
    String query = processor.getQuery(dbAdapter, "myTable", null, Arrays.asList("id", "DATE_CREATED", "TIME_CREATED"), "type = \"CUSTOMER\"", stateManager.getState(Scope.CLUSTER).toMap());
    assertEquals("SELECT * FROM myTable WHERE id > 509 AND DATE_CREATED >= timestamp '2016-03-07 12:34:56' AND TIME_CREATED >= time '12:34:57' AND (type = \"CUSTOMER\")", query);
    // Cover the other path
    dbAdapter = new GenericDatabaseAdapter();
    query = processor.getQuery(dbAdapter, "myTable", null, Arrays.asList("id", "DATE_CREATED", "TIME_CREATED"), "type = \"CUSTOMER\"", stateManager.getState(Scope.CLUSTER).toMap());
    assertEquals("SELECT * FROM myTable WHERE id > 509 AND DATE_CREATED >= '2016-03-07 12:34:56' AND TIME_CREATED >= '12:34:57' AND (type = \"CUSTOMER\")", query);
}
 
Example 15
Source Project: nifi   Source File: GetHDFSEvents.java    License: Apache License 2.0 5 votes vote down vote up
private void updateClusterStateForTxId(StateManager stateManager) {
    try {
        Map<String, String> newState = new HashMap<>(stateManager.getState(Scope.CLUSTER).toMap());
        newState.put(LAST_TX_ID, String.valueOf(lastTxId));
        stateManager.setState(newState, Scope.CLUSTER);
    } catch (IOException e) {
        getLogger().warn("Failed to update cluster state for last txId. It is possible data replication may occur.", e);
    }
}
 
Example 16
Source Project: localization_nifi   Source File: MockValidationContext.java    License: Apache License 2.0 5 votes vote down vote up
public MockValidationContext(final MockProcessContext processContext, final StateManager stateManager, final VariableRegistry variableRegistry) {
    this.context = processContext;
    this.stateManager = stateManager;
    this.variableRegistry = variableRegistry;

    final Map<PropertyDescriptor, String> properties = processContext.getProperties();
    expressionLanguageSupported = new HashMap<>(properties.size());
    for (final PropertyDescriptor descriptor : properties.keySet()) {
        expressionLanguageSupported.put(descriptor.getName(), descriptor.isExpressionLanguageSupported());
    }
}
 
Example 17
Source Project: localization_nifi   Source File: MockReportingContext.java    License: Apache License 2.0 5 votes vote down vote up
public MockReportingContext(final Map<String, ControllerService> controllerServices, final StateManager stateManager, final VariableRegistry variableRegistry) {
    this.controllerServices = new HashMap<>();
    this.stateManager = stateManager;
    this.variableRegistry = variableRegistry;
    for (final Map.Entry<String, ControllerService> entry : controllerServices.entrySet()) {
        this.controllerServices.put(entry.getKey(), new ControllerServiceConfiguration(entry.getValue()));
    }
}
 
Example 18
Source Project: nifi   Source File: ScrollElasticsearchHttp.java    License: Apache License 2.0 5 votes vote down vote up
private void saveScrollId(StateManager stateManager, String scrollId) throws IOException {

        Map<String, String> state = new HashMap<>(2);
        state.put(SCROLL_ID_STATE, scrollId);

        getLogger().debug("Saving state with scrollId of {}", new Object[] { scrollId });
        stateManager.setState(state, Scope.LOCAL);
    }
 
Example 19
Source Project: localization_nifi   Source File: MockProcessContext.java    License: Apache License 2.0 5 votes vote down vote up
public MockProcessContext(final ControllerService component, final MockProcessContext context, final StateManager stateManager, final VariableRegistry variableRegistry) {
    this(component, stateManager, variableRegistry);

    try {
        annotationData = context.getControllerServiceAnnotationData(component);
        final Map<PropertyDescriptor, String> props = context.getControllerServiceProperties(component);
        properties.putAll(props);

        super.addControllerServices(context);
    } catch (IllegalArgumentException e) {
        // do nothing...the service is being loaded
    }
}
 
Example 20
Source Project: nifi   Source File: StandardRemoteProcessGroup.java    License: Apache License 2.0 5 votes vote down vote up
public StandardRemoteProcessGroup(final String id, final String targetUris, final ProcessGroup processGroup, final ProcessScheduler processScheduler,
                                  final BulletinRepository bulletinRepository, final SSLContext sslContext, final NiFiProperties nifiProperties,
                                  final StateManager stateManager) {
    this.nifiProperties = nifiProperties;
    this.stateManager = stateManager;
    this.id = requireNonNull(id);

    this.targetUris = targetUris;
    this.targetId = null;
    this.processGroup = new AtomicReference<>(processGroup);
    this.sslContext = sslContext;
    this.scheduler = processScheduler;
    this.authorizationIssue = "Establishing connection to " + targetUris;

    final String expirationPeriod = nifiProperties.getProperty(NiFiProperties.REMOTE_CONTENTS_CACHE_EXPIRATION, "30 secs");
    remoteContentsCacheExpiration = FormatUtils.getTimeDuration(expirationPeriod, TimeUnit.MILLISECONDS);

    eventReporter = new EventReporter() {
        private static final long serialVersionUID = 1L;

        @Override
        public void reportEvent(final Severity severity, final String category, final String message) {
            final String groupId = StandardRemoteProcessGroup.this.getProcessGroup().getIdentifier();
            final String groupName = StandardRemoteProcessGroup.this.getProcessGroup().getName();
            final String sourceId = StandardRemoteProcessGroup.this.getIdentifier();
            final String sourceName = StandardRemoteProcessGroup.this.getName();
            bulletinRepository.addBulletin(BulletinFactory.createBulletin(groupId, groupName, sourceId, ComponentType.REMOTE_PROCESS_GROUP,
                    sourceName, category, severity.name(), message));
        }
    };

    backgroundThreadExecutor = new FlowEngine(1, "Remote Process Group " + id, true);
}
 
Example 21
Source Project: localization_nifi   Source File: GetSplunk.java    License: Apache License 2.0 5 votes vote down vote up
private void saveState(StateManager stateManager, TimeRange timeRange) throws IOException {
    final String earliest = StringUtils.isBlank(timeRange.getEarliestTime()) ? "" : timeRange.getEarliestTime();
    final String latest = StringUtils.isBlank(timeRange.getLatestTime()) ? "" : timeRange.getLatestTime();

    Map<String,String> state = new HashMap<>(2);
    state.put(EARLIEST_TIME_KEY, earliest);
    state.put(LATEST_TIME_KEY, latest);

    getLogger().debug("Saving state with earliestTime of {} and latestTime of {}", new Object[] {earliest, latest});
    stateManager.setState(state, Scope.CLUSTER);
}
 
Example 22
Source Project: localization_nifi   Source File: MonitorActivity.java    License: Apache License 2.0 5 votes vote down vote up
@OnStopped
public void onStopped(final ProcessContext context) {
    if (getNodeTypeProvider().isPrimary()) {
        final StateManager stateManager = context.getStateManager();
        try {
            stateManager.clear(Scope.CLUSTER);
        } catch (IOException e) {
            getLogger().error("Failed to clear cluster state due to " + e, e);
        }
    }
}
 
Example 23
Source Project: localization_nifi   Source File: TestGenerateTableFetch.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testBackwardsCompatibilityStateKeyStaticTableDynamicMaxValues() throws Exception {
    // load test data to database
    final Connection con = ((DBCPService) runner.getControllerService("dbcp")).getConnection();
    Statement stmt = con.createStatement();

    try {
        stmt.execute("drop table TEST_QUERY_DB_TABLE");
    } catch (final SQLException sqle) {
        // Ignore this error, probably a "table does not exist" since Derby doesn't yet support DROP IF EXISTS [DERBY-4842]
    }

    stmt.execute("create table TEST_QUERY_DB_TABLE (id integer not null, bucket integer not null)");
    stmt.execute("insert into TEST_QUERY_DB_TABLE (id, bucket) VALUES (0, 0)");
    stmt.execute("insert into TEST_QUERY_DB_TABLE (id, bucket) VALUES (1, 0)");

    runner.setProperty(GenerateTableFetch.TABLE_NAME, "TEST_QUERY_DB_TABLE");
    runner.setIncomingConnection(true);
    runner.setProperty(GenerateTableFetch.MAX_VALUE_COLUMN_NAMES, "${maxValueCol}");
    runner.enqueue("".getBytes(), new HashMap<String, String>() {{
        put("maxValueCol", "id");
    }});

    // Pre-populate the state with a key for column name (not fully-qualified)
    StateManager stateManager = runner.getStateManager();
    stateManager.setState(new HashMap<String, String>() {{
        put("id", "0");
    }}, Scope.CLUSTER);

    // Pre-populate the column type map with an entry for id (not fully-qualified)
    processor.columnTypeMap.put("id", 4);

    runner.run();

    runner.assertAllFlowFilesTransferred(REL_SUCCESS, 1);
    MockFlowFile flowFile = runner.getFlowFilesForRelationship(REL_SUCCESS).get(0);
    assertEquals("SELECT * FROM TEST_QUERY_DB_TABLE WHERE id > 0 ORDER BY id FETCH NEXT 10000 ROWS ONLY", new String(flowFile.toByteArray()));
}
 
Example 24
Source Project: nifi   Source File: ScrollElasticsearchHttp.java    License: Apache License 2.0 5 votes vote down vote up
private String loadScrollId(StateManager stateManager) throws IOException {
    final StateMap stateMap = stateManager.getState(Scope.LOCAL);

    if (stateMap.getVersion() < 0) {
        getLogger().debug("No previous state found");
        return null;
    }

    final String scrollId = stateMap.get(SCROLL_ID_STATE);
    getLogger().debug("Loaded state with scrollId {}", new Object[] { scrollId });

    return scrollId;
}
 
Example 25
Source Project: localization_nifi   Source File: GetHDFSEvents.java    License: Apache License 2.0 5 votes vote down vote up
private void updateClusterStateForTxId(StateManager stateManager) {
    try {
        Map<String, String> newState = new HashMap<>(stateManager.getState(Scope.CLUSTER).toMap());
        newState.put(LAST_TX_ID, String.valueOf(lastTxId));
        stateManager.setState(newState, Scope.CLUSTER);
    } catch (IOException e) {
        getLogger().warn("Failed to update cluster state for last txId. It is possible data replication may occur.", e);
    }
}
 
Example 26
Source Project: nifi   Source File: ScriptedActionHandlerTest.java    License: Apache License 2.0 5 votes vote down vote up
private MockScriptedActionHandler initTask(String scriptFile) throws InitializationException {

        final MockScriptedActionHandler actionHandler = new MockScriptedActionHandler();
        context = mock(ConfigurationContext.class);
        StateManager stateManager = new MockStateManager(actionHandler);

        final ComponentLog logger = mock(ComponentLog.class);
        final ControllerServiceInitializationContext initContext = new MockControllerServiceInitializationContext(actionHandler, UUID.randomUUID().toString(), logger, stateManager);
        actionHandler.initialize(initContext);

        // Call something that sets up the ScriptingComponentHelper, so we can mock it
        actionHandler.getSupportedPropertyDescriptors();

        Map<PropertyDescriptor, String> properties = new HashMap<>();
        properties.put(actionHandler.getScriptingComponentHelper().SCRIPT_ENGINE, actionHandler.getScriptingComponentHelper().SCRIPT_ENGINE.getName());
        properties.put(ScriptingComponentUtils.SCRIPT_FILE, ScriptingComponentUtils.SCRIPT_FILE.getName());
        properties.put(ScriptingComponentUtils.SCRIPT_BODY, ScriptingComponentUtils.SCRIPT_BODY.getName());
        properties.put(ScriptingComponentUtils.MODULES, ScriptingComponentUtils.MODULES.getName());
        when(context.getProperties()).thenReturn(properties);

        when(context.getProperty(actionHandler.getScriptingComponentHelper().SCRIPT_ENGINE))
                .thenReturn(new MockPropertyValue("Groovy"));
        when(context.getProperty(ScriptingComponentUtils.SCRIPT_FILE))
                .thenReturn(new MockPropertyValue(scriptFile));
        when(context.getProperty(ScriptingComponentUtils.SCRIPT_BODY))
                .thenReturn(new MockPropertyValue(null));
        when(context.getProperty(ScriptingComponentUtils.MODULES))
                .thenReturn(new MockPropertyValue(null));
        try {
            actionHandler.onEnabled(context);
        } catch (Exception e) {
            e.printStackTrace();
            fail("onEnabled error: " + e.getMessage());
        }
        return actionHandler;
    }
 
Example 27
private void clearState(final String componentId) {
    try {
        final StateManager manager = stateManagerProvider.getStateManager(componentId);
        if (manager == null) {
            throw new ResourceNotFoundException(String.format("State for the specified component %s could not be found.", componentId));
        }

        // clear both state's at the same time
        manager.clear(Scope.CLUSTER);
        manager.clear(Scope.LOCAL);
    } catch (final IOException ioe) {
        throw new IllegalStateException(String.format("Unable to clear the state for the specified component %s: %s", componentId, ioe), ioe);
    }
}
 
Example 28
public StandardControllerServiceInitializationContext(
        final String identifier, final ComponentLog logger,
        final ControllerServiceProvider serviceProvider, final StateManager stateManager,
        final KerberosConfig kerberosConfig, final NodeTypeProvider nodeTypeProvider) {
    this.id = identifier;
    this.logger = logger;
    this.serviceProvider = serviceProvider;
    this.stateManager = stateManager;
    this.kerberosConfig = kerberosConfig;
    this.nodeTypeProvider = nodeTypeProvider;
}
 
Example 29
Source Project: nifi   Source File: GetHBase.java    License: Apache License 2.0 5 votes vote down vote up
private ScanResult getState(final StateManager stateManager) throws IOException {
    final StateMap stateMap = stateManager.getState(Scope.CLUSTER);
    if (stateMap.getVersion() < 0) {
        return null;
    }

    return ScanResult.fromFlatMap(stateMap.toMap());
}
 
Example 30
Source Project: nifi   Source File: StandardStateManagerProvider.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns the State Manager that has been created for the given component ID, or <code>null</code> if none exists
 *
 * @return the StateManager that can be used by the component with the given ID, or <code>null</code> if none exists
 */
@Override
public synchronized StateManager getStateManager(final String componentId) {
    StateManager stateManager = stateManagers.get(componentId);
    if (stateManager != null) {
        return stateManager;
    }

    stateManager = new StandardStateManager(localStateProvider, clusterStateProvider, componentId);
    stateManagers.put(componentId, stateManager);
    return stateManager;
}