org.apache.nifi.controller.ConfigurationContext Java Examples

The following examples show how to use org.apache.nifi.controller.ConfigurationContext. 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: StandardProcessorTestRunner.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
@Override
public void enableControllerService(final ControllerService service) {
    final ControllerServiceConfiguration configuration = context.getConfiguration(service.getIdentifier());
    if (configuration == null) {
        throw new IllegalArgumentException("Controller Service " + service + " is not known");
    }

    if (configuration.isEnabled()) {
        throw new IllegalStateException("Cannot enable Controller Service " + service + " because it is not disabled");
    }

    try {
        final ConfigurationContext configContext = new MockConfigurationContext(service, configuration.getProperties(), context,variableRegistry);
        ReflectionUtils.invokeMethodsWithAnnotation(OnEnabled.class, service, configContext);
    } catch (final InvocationTargetException ite) {
        ite.getCause().printStackTrace();
        Assert.fail("Failed to enable Controller Service " + service + " due to " + ite.getCause());
    } catch (final Exception e) {
        e.printStackTrace();
        Assert.fail("Failed to enable Controller Service " + service + " due to " + e);
    }

    configuration.setEnabled(true);
}
 
Example #2
Source File: JettyWebSocketServer.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
private SslContextFactory createSslFactory(final ConfigurationContext context) {
    final SSLContextService sslService = context.getProperty(SSL_CONTEXT).asControllerService(SSLContextService.class);

    final String clientAuthValue = context.getProperty(CLIENT_AUTH).getValue();
    final boolean need;
    final boolean want;
    if (CLIENT_NEED.equals(clientAuthValue)) {
        need = true;
        want = false;
    } else if (CLIENT_WANT.equals(clientAuthValue)) {
        need = false;
        want = true;
    } else {
        need = false;
        want = false;
    }

    final SslContextFactory sslFactory = (sslService == null) ? null : createSslFactory(sslService, need, want);
    return sslFactory;
}
 
Example #3
Source File: ScriptedReportingTask.java    From nifi with Apache License 2.0 6 votes vote down vote up
/**
 * Performs setup operations when the processor is scheduled to run. This includes evaluating the processor's
 * properties, as well as reloading the script (from file or the "Script Body" property)
 *
 * @param context the context in which to perform the setup operations
 */
@OnScheduled
public void setup(final ConfigurationContext context) {
    scriptingComponentHelper.setupVariables(context);

    // Create a script engine for each possible task
    scriptingComponentHelper.setup(1, getLogger());
    scriptToRun = scriptingComponentHelper.getScriptBody();

    try {
        String scriptPath = scriptingComponentHelper.getScriptPath();
        if (scriptToRun == null && scriptPath != null) {
            try (final FileInputStream scriptStream = new FileInputStream(scriptPath)) {
                scriptToRun = IOUtils.toString(scriptStream, Charset.defaultCharset());
            }
        }
    } catch (IOException ioe) {
        throw new ProcessException(ioe);
    }

    vmMetrics = JmxJvmMetrics.getInstance();
}
 
Example #4
Source File: SchemaRegistryRecordSetWriter.java    From nifi with Apache License 2.0 6 votes vote down vote up
@OnEnabled
public void storeSchemaWriteStrategy(final ConfigurationContext context) {
    this.configurationContext = context;

    // If Schema Protocol Version is specified without EL then we can create it up front, otherwise when
    // EL is present we will re-create it later so we can re-evaluate the EL against the incoming variables

    final String strategy = context.getProperty(getSchemaWriteStrategyDescriptor()).getValue();
    if (strategy != null) {
        final RecordSchemaCacheService recordSchemaCacheService = context.getProperty(SCHEMA_CACHE).asControllerService(RecordSchemaCacheService.class);

        final PropertyValue protocolVersionValue = getConfigurationContext().getProperty(SCHEMA_PROTOCOL_VERSION);
        if (!protocolVersionValue.isExpressionLanguagePresent()) {
            final int protocolVersion = context.getProperty(SCHEMA_PROTOCOL_VERSION).asInteger();
            this.schemaAccessWriter = createSchemaWriteStrategy(strategy, protocolVersion, recordSchemaCacheService);
        }
    }
}
 
Example #5
Source File: AbstractEasyRulesEngineController.java    From nifi with Apache License 2.0 6 votes vote down vote up
@OnEnabled
public void onEnabled(final ConfigurationContext context) throws InitializationException {
    final String rulesFile = context.getProperty(RULES_FILE_PATH).getValue();
    final String rulesBody = context.getProperty(RULES_BODY).getValue();
    final String rulesFileType = context.getProperty(RULES_FILE_TYPE).getValue();
    rulesFileFormat = context.getProperty(RULES_FILE_FORMAT).getValue();
    ignoreConditionErrors = context.getProperty(IGNORE_CONDITION_ERRORS).asBoolean();
    filterRules = context.getProperty(FILTER_RULES_MISSING_FACTS).asBoolean();

    try{
        if(StringUtils.isEmpty(rulesFile)){
            rules = RulesFactory.createRulesFromString(rulesBody, rulesFileType, rulesFileFormat);
        }else{
            rules = RulesFactory.createRulesFromFile(rulesFile, rulesFileType, rulesFileFormat);
        }
    } catch (Exception fex){
        throw new InitializationException(fex);
    }
}
 
Example #6
Source File: RestLookupService.java    From nifi with Apache License 2.0 6 votes vote down vote up
private void setAuthenticator(OkHttpClient.Builder okHttpClientBuilder, ConfigurationContext context) {
    final String authUser = trimToEmpty(context.getProperty(PROP_BASIC_AUTH_USERNAME).evaluateAttributeExpressions().getValue());
    this.basicUser = authUser;


    isDigest = context.getProperty(PROP_DIGEST_AUTH).asBoolean();
    final String authPass = trimToEmpty(context.getProperty(PROP_BASIC_AUTH_PASSWORD).evaluateAttributeExpressions().getValue());
    this.basicPass = authPass;
    // If the username/password properties are set then check if digest auth is being used
    if (!authUser.isEmpty() && isDigest) {

        /*
         * OkHttp doesn't have built-in Digest Auth Support. A ticket for adding it is here[1] but they authors decided instead to rely on a 3rd party lib.
         *
         * [1] https://github.com/square/okhttp/issues/205#issuecomment-154047052
         */
        final Map<String, CachingAuthenticator> authCache = new ConcurrentHashMap<>();
        com.burgstaller.okhttp.digest.Credentials credentials = new com.burgstaller.okhttp.digest.Credentials(authUser, authPass);
        final DigestAuthenticator digestAuthenticator = new DigestAuthenticator(credentials);

        okHttpClientBuilder.interceptors().add(new AuthenticationCacheInterceptor(authCache));
        okHttpClientBuilder.authenticator(new CachingAuthenticatorDecorator(digestAuthenticator, authCache));
    }
}
 
Example #7
Source File: ElasticSearchLookupService.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Override
@OnEnabled
public void onEnabled(final ConfigurationContext context) {
    clientService = context.getProperty(CLIENT_SERVICE).asControllerService(ElasticSearchClientService.class);
    index = context.getProperty(INDEX).evaluateAttributeExpressions().getValue();
    type  = context.getProperty(TYPE).evaluateAttributeExpressions().getValue();
    mapper = new ObjectMapper();

    List<PropertyDescriptor> dynamic = context.getProperties().entrySet().stream()
        .filter( e -> e.getKey().isDynamic())
        .map(e -> e.getKey())
        .collect(Collectors.toList());

    Map<String, RecordPath> _temp = new HashMap<>();
    for (PropertyDescriptor desc : dynamic) {
        String value = context.getProperty(desc).getValue();
        String name  = desc.getName();
        _temp.put(name, RecordPath.compile(value));
    }

    mappings = new ConcurrentHashMap<>(_temp);

    super.onEnabled(context);
}
 
Example #8
Source File: KafkaRecordSink_2_0.java    From nifi with Apache License 2.0 6 votes vote down vote up
@OnEnabled
public void onEnabled(final ConfigurationContext context) throws InitializationException {
    topic = context.getProperty(TOPIC).evaluateAttributeExpressions().getValue();
    writerFactory = context.getProperty(RecordSinkService.RECORD_WRITER_FACTORY).asControllerService(RecordSetWriterFactory.class);
    maxMessageSize = context.getProperty(MAX_REQUEST_SIZE).asDataSize(DataUnit.B).intValue();
    maxAckWaitMillis = context.getProperty(ACK_WAIT_TIME).asTimePeriod(TimeUnit.MILLISECONDS);

    final String charsetName = context.getProperty(MESSAGE_HEADER_ENCODING).evaluateAttributeExpressions().getValue();
    final Charset charset = Charset.forName(charsetName);

    final Map<String, Object> kafkaProperties = new HashMap<>();
    buildCommonKafkaProperties(context, ProducerConfig.class, kafkaProperties);
    kafkaProperties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, ByteArraySerializer.class.getName());
    kafkaProperties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, ByteArraySerializer.class.getName());
    kafkaProperties.put("max.request.size", String.valueOf(maxMessageSize));

    try {
        producer = createProducer(kafkaProperties);
    } catch (Exception e) {
        getLogger().error("Could not create Kafka producer due to {}", new Object[]{e.getMessage()}, e);
        throw new InitializationException(e);
    }
}
 
Example #9
Source File: HBase_1_1_2_ClientService.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
@OnEnabled
public void onEnabled(final ConfigurationContext context) throws InitializationException, IOException, InterruptedException {
    this.connection = createConnection(context);

    // connection check
    if (this.connection != null) {
        final Admin admin = this.connection.getAdmin();
        if (admin != null) {
            admin.listTableNames();
        }

        // if we got here then we have a successful connection, so if we have a ugi then start a renewer
        if (ugi != null) {
            final String id = getClass().getSimpleName();
            renewer = SecurityUtil.startTicketRenewalThread(id, ugi, TICKET_RENEWAL_PERIOD, getLogger());
        }
    }
}
 
Example #10
Source File: CouchbaseClusterService.java    From nifi with Apache License 2.0 6 votes vote down vote up
/**
 * Establish a connection to a Couchbase cluster.
 * @param context the configuration context
 * @throws InitializationException if unable to connect a Couchbase cluster
 */
@OnEnabled
public void onConfigured(final ConfigurationContext context) throws InitializationException {

    bucketPasswords = new HashMap<>();
    for(PropertyDescriptor p : context.getProperties().keySet()){
        if(p.isDynamic() && p.getName().startsWith(DYNAMIC_PROP_BUCKET_PASSWORD)){
            String bucketName = p.getName().substring(DYNAMIC_PROP_BUCKET_PASSWORD.length());
            String password = context.getProperty(p).evaluateAttributeExpressions().getValue();
            bucketPasswords.put(bucketName, password);
        }
    }

    final String userName = context.getProperty(USER_NAME).evaluateAttributeExpressions().getValue();
    final String userPassword = context.getProperty(USER_PASSWORD).evaluateAttributeExpressions().getValue();

    try {
        cluster = CouchbaseCluster.fromConnectionString(context.getProperty(CONNECTION_STRING).evaluateAttributeExpressions().getValue());
        if (!StringUtils.isEmpty(userName) && !StringUtils.isEmpty(userPassword)) {
            cluster.authenticate(userName, userPassword);
        }
    } catch(CouchbaseException e) {
        throw new InitializationException(e);
    }
}
 
Example #11
Source File: StandardS3EncryptionService.java    From nifi with Apache License 2.0 6 votes vote down vote up
@OnEnabled
public void onConfigured(final ConfigurationContext context) throws InitializationException {
    final String newStrategyName = context.getProperty(ENCRYPTION_STRATEGY).getValue();
    final String newKeyValue = context.getProperty(ENCRYPTION_VALUE).evaluateAttributeExpressions().getValue();
    final S3EncryptionStrategy newEncryptionStrategy = NAMED_STRATEGIES.get(newStrategyName);
    String newKmsRegion = null;

    if (context.getProperty(KMS_REGION) != null ) {
        newKmsRegion = context.getProperty(KMS_REGION).getValue();
    }

    if (newEncryptionStrategy == null) {
        final String msg = "No encryption strategy found for name: " + strategyName;
        logger.warn(msg);
        throw new InitializationException(msg);
    }

    strategyName = newStrategyName;
    encryptionStrategy = newEncryptionStrategy;
    keyValue = newKeyValue;
    kmsRegion = newKmsRegion;
}
 
Example #12
Source File: JMSConnectionFactoryProvider.java    From solace-integration-guides with Apache License 2.0 6 votes vote down vote up
/**
 *
 */
@OnEnabled
public void enable(ConfigurationContext context) throws InitializationException {
    try {
        if (!this.configured) {
            if (logger.isInfoEnabled()) {
                logger.info("Configuring " + this.getClass().getSimpleName() + " for '"
                        + context.getProperty(CONNECTION_FACTORY_IMPL).evaluateAttributeExpressions().getValue() + "' to be connected to '"
                        + BROKER_URI + "'");
            }
            // will load user provided libraries/resources on the classpath
            Utils.addResourcesToClasspath(context.getProperty(CLIENT_LIB_DIR_PATH).evaluateAttributeExpressions().getValue());

            this.createConnectionFactoryInstance(context);

            this.setConnectionFactoryProperties(context);
        }
        this.configured = true;
    } catch (Exception e) {
        logger.error("Failed to configure " + this.getClass().getSimpleName(), e);
        this.configured = false;
        throw new IllegalStateException(e);
    }
}
 
Example #13
Source File: AWSCredentialsProviderControllerService.java    From nifi with Apache License 2.0 5 votes vote down vote up
@OnEnabled
public void onConfigured(final ConfigurationContext context) throws InitializationException {
    final Map<PropertyDescriptor, String> properties = context.getProperties();
    properties.keySet().forEach(propertyDescriptor -> {
        if (propertyDescriptor.isExpressionLanguageSupported()) {
            properties.put(propertyDescriptor,
                    context.getProperty(propertyDescriptor).evaluateAttributeExpressions().getValue());
        }
    });
    credentialsProvider = credentialsProviderFactory.getCredentialsProvider(properties);
    getLogger().debug("Using credentials provider: " + credentialsProvider.getClass());
}
 
Example #14
Source File: ScriptedRecordSinkTest.java    From nifi with Apache License 2.0 5 votes vote down vote up
private MockScriptedRecordSink initTask() throws InitializationException {

        final MockScriptedRecordSink recordSink = new MockScriptedRecordSink();
        ConfigurationContext context = mock(ConfigurationContext.class);
        StateManager stateManager = new MockStateManager(recordSink);

        final PropertyValue pValue = mock(StandardPropertyValue.class);
        MockRecordWriter writer = new MockRecordWriter(null, false); // No header, don"t quote values
        when(context.getProperty(RecordSinkService.RECORD_WRITER_FACTORY)).thenReturn(pValue);
        when(pValue.asControllerService(RecordSetWriterFactory.class)).thenReturn(writer);


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

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

        when(context.getProperty(recordSink.getScriptingComponentHelper().SCRIPT_ENGINE))
                .thenReturn(new MockPropertyValue("Groovy"));
        when(context.getProperty(ScriptingComponentUtils.SCRIPT_FILE))
                .thenReturn(new MockPropertyValue("src/test/resources/groovy/test_record_sink.groovy"));
        when(context.getProperty(ScriptingComponentUtils.SCRIPT_BODY))
                .thenReturn(new MockPropertyValue(null));
        when(context.getProperty(ScriptingComponentUtils.MODULES))
                .thenReturn(new MockPropertyValue(null));
        try {
            recordSink.onEnabled(context);
        } catch (Exception e) {
            e.printStackTrace();
            fail("onEnabled error: " + e.getMessage());
        }
        return recordSink;
    }
 
Example #15
Source File: Syslog5424Reader.java    From nifi with Apache License 2.0 5 votes vote down vote up
@OnEnabled
public void onEnabled(final ConfigurationContext context) {
    final String charsetName = context.getProperty(CHARSET).getValue();
    includeRaw = context.getProperty(ADD_RAW).asBoolean();
    parser = new StrictSyslog5424Parser(Charset.forName(charsetName), NilHandlingPolicy.NULL, NifiStructuredDataPolicy.MAP_OF_MAPS, new SimpleKeyProvider());
    recordSchema = createRecordSchema();
}
 
Example #16
Source File: JNDIConnectionFactoryProvider.java    From solace-integration-guides with Apache License 2.0 5 votes vote down vote up
/**
 * This operation follows standard bean convention by matching property name to its corresponding 'setter' method.
 * Once the method was located it is invoked to set the corresponding property to a value provided by during service
 * configuration. For example, 'channel' property will correspond to 'setChannel(..) method and 'queueManager'
 * property will correspond to setQueueManager(..) method with a single argument.
 *
 * There are also few adjustments to accommodate well known brokers. For example ActiveMQ ConnectionFactory accepts
 * address of the Message Broker in a form of URL while IBMs in the form of host/port pair (more common). So this
 * method will use value retrieved from the 'BROKER_URI' static property 'as is' if ConnectionFactory implementation
 * is coming from ActiveMQ and for all others (for now) the 'BROKER_URI' value will be split on ':' and the
 * resulting pair will be used to execute setHostName(..) and setPort(..) methods on the provided ConnectionFactory.
 * This may need to be maintained and adjusted to accommodate other implementation of ConnectionFactory, but only
 * for URL/Host/Port issue. All other properties are set as dynamic properties where user essentially provides both
 * property name and value, The bean convention is also explained in user manual for this component with links
 * pointing to documentation of various ConnectionFactories.
 *
 * @see #setProperty(String, String) method
 */
private void setConnectionFactoryProperties(ConfigurationContext context) {
    for (final Entry<PropertyDescriptor, String> entry : context.getProperties().entrySet()) {
        logger.info("entry = " + entry.toString());
        PropertyDescriptor descriptor = entry.getKey();
        String propertyName = descriptor.getName();
        if (descriptor.isDynamic()) {
            this.setProperty(propertyName, entry.getValue());
        } else {
            if (propertyName.equals(BROKER)) {
                if (context.getProperty(CONNECTION_FACTORY_IMPL).evaluateAttributeExpressions().getValue().startsWith("org.apache.activemq")) {
                    this.setProperty("brokerURL", entry.getValue());
                } else if (isSolace(context)) {
                    // TODO 
                    ;
                } else {

                    String[] hostPort = entry.getValue().split(":");
                    if (hostPort.length == 2) {
                        this.setProperty("hostName", hostPort[0]);
                        this.setProperty("port", hostPort[1]);
                    } else if (hostPort.length != 2) {
                        this.setProperty("serverUrl", entry.getValue()); // for tibco
                    } else {
                        throw new IllegalArgumentException("Failed to parse broker url: " + entry.getValue());
                    }
                }
                SSLContextService sc = context.getProperty(SSL_CONTEXT_SERVICE).asControllerService(SSLContextService.class);
                if (sc != null) {
                    SSLContext ssl = sc.createSSLContext(ClientAuth.NONE);
                    this.setProperty("sSLSocketFactory", ssl.getSocketFactory());
                }
            } // ignore 'else', since it's the only non-dynamic property that is relevant to CF configuration
        }
    }
}
 
Example #17
Source File: AbstractHBaseLookupService.java    From nifi with Apache License 2.0 5 votes vote down vote up
@OnEnabled
public void onEnabled(final ConfigurationContext context) throws InitializationException, IOException, InterruptedException {
    this.hBaseClientService = context.getProperty(HBASE_CLIENT_SERVICE).asControllerService(HBaseClientService.class);
    this.tableName = context.getProperty(TABLE_NAME).getValue();
    this.columns = getColumns(context.getProperty(RETURN_COLUMNS).getValue());
    this.charset = Charset.forName(context.getProperty(CHARSET).getValue());
    this.authorizations = VisibilityLabelUtils.getAuthorizations(context);
}
 
Example #18
Source File: AbstractCouchbaseLookupService.java    From nifi with Apache License 2.0 5 votes vote down vote up
@OnEnabled
public void onEnabled(final ConfigurationContext context) throws InitializationException {

    couchbaseClusterService = context.getProperty(COUCHBASE_CLUSTER_SERVICE)
            .asControllerService(CouchbaseClusterControllerService.class);
    bucketName = context.getProperty(BUCKET_NAME).evaluateAttributeExpressions().getValue();
}
 
Example #19
Source File: TestStandardProcessScheduler.java    From nifi with Apache License 2.0 5 votes vote down vote up
@OnEnabled
public void enable(final ConfigurationContext context) {
    try {
        Thread.sleep(random.nextInt(20));
    } catch (final InterruptedException e) {
        Thread.currentThread().interrupt();
    }
}
 
Example #20
Source File: SchemaRegistryService.java    From nifi with Apache License 2.0 5 votes vote down vote up
@OnEnabled
public void storeSchemaAccessStrategy(final ConfigurationContext context) {
    this.configurationContext = context;

    final SchemaRegistry schemaRegistry = context.getProperty(SCHEMA_REGISTRY).asControllerService(SchemaRegistry.class);

    final PropertyDescriptor descriptor = getSchemaAcessStrategyDescriptor();
    final String schemaAccess = context.getProperty(descriptor).getValue();
    this.schemaAccessStrategy = getSchemaAccessStrategy(schemaAccess, schemaRegistry, context);
}
 
Example #21
Source File: ITPutS3Object.java    From nifi with Apache License 2.0 5 votes vote down vote up
private static TestRunner createEncryptionTestRunner(Processor processor, String strategyName, String keyIdOrMaterial) throws InitializationException {
    final TestRunner runner = TestRunners.newTestRunner(processor);
    final ConfigurationContext context = mock(ConfigurationContext.class);

    runner.setProperty(PutS3Object.CREDENTIALS_FILE, CREDENTIALS_FILE);
    runner.setProperty(PutS3Object.REGION, REGION);
    runner.setProperty(PutS3Object.BUCKET, BUCKET_NAME);

    if (strategyName != null) {
        final StandardS3EncryptionService service = new StandardS3EncryptionService();
        runner.addControllerService(PutS3Object.ENCRYPTION_SERVICE.getName(), service);
        runner.setProperty(PutS3Object.ENCRYPTION_SERVICE, service.getIdentifier());

        runner.setProperty(service, StandardS3EncryptionService.ENCRYPTION_STRATEGY, strategyName);
        runner.setProperty(service, StandardS3EncryptionService.ENCRYPTION_VALUE, keyIdOrMaterial);
        runner.setProperty(service, StandardS3EncryptionService.KMS_REGION, REGION);

        when(context.getProperty(StandardS3EncryptionService.ENCRYPTION_STRATEGY)).thenReturn(new MockPropertyValue(strategyName));
        when(context.getProperty(StandardS3EncryptionService.ENCRYPTION_VALUE)).thenReturn(new MockPropertyValue(keyIdOrMaterial));
        when(context.getProperty(StandardS3EncryptionService.KMS_REGION)).thenReturn(new MockPropertyValue(REGION));

        service.onConfigured(context);
        runner.enableControllerService(service);
    }

    return runner;
}
 
Example #22
Source File: AbstractActionHandlerService.java    From nifi with Apache License 2.0 5 votes vote down vote up
@OnEnabled
public void onEnabled(final ConfigurationContext context) throws InitializationException {
    String actionTypes = context.getProperty(ENFORCE_ACTION_TYPE).evaluateAttributeExpressions().getValue();
    if(StringUtils.isNotEmpty(actionTypes)){
        enforceActionTypes = Arrays.stream(actionTypes.split(","))
                                   .map(String::trim)
                                   .filter(StringUtils::isNotEmpty)
                                   .collect(Collectors.toList());
    }
    String level = context.getProperty(ENFORCE_ACTION_TYPE_LEVEL).getValue();
    if(StringUtils.isNotEmpty(level)) {
        enforceActionTypeLevel = EnforceActionTypeLevel.valueOf(level);
    }
}
 
Example #23
Source File: VisibilityLabelUtils.java    From nifi with Apache License 2.0 5 votes vote down vote up
static List<String> getAuthorizations(ConfigurationContext context) {
    List<String> tokens = new ArrayList<>();
    String authorizationString = context.getProperty(AUTHORIZATIONS).isSet()
            ? context.getProperty(AUTHORIZATIONS).getValue()
            : "";
    if (!StringUtils.isEmpty(authorizationString)) {
        tokens = Arrays.asList(authorizationString.split(",[\\s]*"));
    }

    return tokens;
}
 
Example #24
Source File: CSVRecordSetWriter.java    From nifi with Apache License 2.0 5 votes vote down vote up
@OnEnabled
public void storeStaticProperties(final ConfigurationContext context) {
    this.context = context;

    this.includeHeader = context.getProperty(CSVUtils.INCLUDE_HEADER_LINE).asBoolean();
    this.charSet = context.getProperty(CSVUtils.CHARSET).getValue();

    if (!CSVUtils.isDynamicCSVFormat(context)) {
        this.csvFormat = CSVUtils.createCSVFormat(context, Collections.emptyMap());
    } else {
        this.csvFormat = null;
    }
}
 
Example #25
Source File: MetricsReportingTask.java    From nifi with Apache License 2.0 5 votes vote down vote up
/**
 * Populate {@link #reporter} using the {@link MetricReporterService}. If the reporter is active already,
 * do nothing.
 *
 * @param context used for accessing the controller service.
 */
@OnScheduled
public void connect(ConfigurationContext context) {
    if (reporter == null) {
        reporter = ((MetricReporterService) context.getProperty(REPORTER_SERVICE).asControllerService())
                .createReporter(metricRegistry);
    }
}
 
Example #26
Source File: VolatileSchemaCache.java    From nifi with Apache License 2.0 5 votes vote down vote up
@OnEnabled
public void setup(final ConfigurationContext context) {
    final int maxSize = context.getProperty(MAX_SIZE).evaluateAttributeExpressions().asInteger();

    cache = Caffeine.newBuilder()
        .maximumSize(maxSize)
        .build();
}
 
Example #27
Source File: RedisDistributedMapCacheClientService.java    From nifi with Apache License 2.0 5 votes vote down vote up
@OnEnabled
public void onEnabled(final ConfigurationContext context) {
    this.redisConnectionPool = context.getProperty(REDIS_CONNECTION_POOL).asControllerService(RedisConnectionPool.class);
    this.ttl = context.getProperty(TTL).asTimePeriod(TimeUnit.SECONDS);

    if (ttl == 0) {
        this.ttl = -1L;
    }
}
 
Example #28
Source File: EasyRulesEngineService.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Override
@OnEnabled
public void onEnabled(final ConfigurationContext context) throws InitializationException {
    super.onEnabled(context);
    EasyRulesEngine easyRulesEngine = (EasyRulesEngine) getRulesEngine();
    List<RuleListener> ruleListeners = new ArrayList<>();
    ruleListeners.add(new EasyRulesListener(getLogger()));
    easyRulesEngine.setRuleListeners(ruleListeners);
    rulesEngine = easyRulesEngine;
}
 
Example #29
Source File: KuduLookupService.java    From nifi with Apache License 2.0 5 votes vote down vote up
protected void createKuduClient(ConfigurationContext context) throws LoginException {
    final String kuduMasters = context.getProperty(KUDU_MASTERS).evaluateAttributeExpressions().getValue();
    final KerberosCredentialsService credentialsService = context.getProperty(KERBEROS_CREDENTIALS_SERVICE).asControllerService(KerberosCredentialsService.class);

    if (credentialsService != null) {
        final String keytab = credentialsService.getKeytab();
        final String principal = credentialsService.getPrincipal();
        kerberosUser = loginKerberosUser(principal, keytab);

        final KerberosAction<KuduClient> kerberosAction = new KerberosAction<>(kerberosUser, () -> buildClient(kuduMasters, context), getLogger());
        this.kuduClient = kerberosAction.execute();
    } else {
        this.kuduClient = buildClient(kuduMasters, context);
    }
}
 
Example #30
Source File: DistributedCacheServer.java    From nifi with Apache License 2.0 5 votes vote down vote up
@OnEnabled
public void startServer(final ConfigurationContext context) throws IOException {
    if (cacheServer == null) {
        cacheServer = createCacheServer(context);
        cacheServer.start();
    }
}