Java Code Examples for org.apache.nifi.components.PropertyValue#isSet()

The following examples show how to use org.apache.nifi.components.PropertyValue#isSet() . 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: ShellUserGroupProvider.java    From nifi with Apache License 2.0 6 votes vote down vote up
private long getDelayProperty(AuthorizerConfigurationContext authContext, String propertyName, String defaultValue) {
    final PropertyValue intervalProperty = authContext.getProperty(propertyName);
    final String propertyValue;
    final long syncInterval;

    if (intervalProperty.isSet()) {
        propertyValue = intervalProperty.getValue();
    } else {
        propertyValue = defaultValue;
    }

    try {
        syncInterval = Math.round(FormatUtils.getPreciseTimeDuration(propertyValue, TimeUnit.MILLISECONDS));
    } catch (final IllegalArgumentException ignored) {
        throw new AuthorizerCreationException(String.format("The %s '%s' is not a valid time interval.", propertyName, propertyValue));
    }

    if (syncInterval < MINIMUM_SYNC_INTERVAL_MILLISECONDS) {
        throw new AuthorizerCreationException(String.format("The %s '%s' is below the minimum value of '%d ms'", propertyName, propertyValue, MINIMUM_SYNC_INTERVAL_MILLISECONDS));
    }
    return syncInterval;
}
 
Example 2
Source File: PrometheusReportingTask.java    From nifi-prometheus-reporter with Apache License 2.0 6 votes vote down vote up
/**
 * Searches all ProcessGroups defined in a PropertyValue as a comma-separated list of ProcessorGroup-IDs.
 * Therefore blanks are trimmed and new-line characters are removed! Processors that can not be found are ignored.
 *
 * @return List of all ProcessorGroups that were found.
 * If no groupIDs are defined or none of them could be found an array containing the root-DataFlow will be returned.
 */
private ProcessGroupStatus[] searchProcessGroups(final ReportingContext context, PropertyValue value) {
    if (value.isSet()) {
        String content = value.evaluateAttributeExpressions().getValue();

        ProcessGroupStatus[] groups = Arrays
                .stream(content.replace("\n", "").split(","))
                .map(String::trim)
                .map(context.getEventAccess()::getGroupStatus)
                .filter(Objects::nonNull)
                .toArray(ProcessGroupStatus[]::new);

        return groups.length > 0 ? groups : new ProcessGroupStatus[]{context.getEventAccess().getControllerStatus()};
    } else {
        return new ProcessGroupStatus[]{context.getEventAccess().getControllerStatus()};
    }
}
 
Example 3
Source File: PutAccumuloRecord.java    From nifi with Apache License 2.0 6 votes vote down vote up
/**
 * Adapted from HBASEUtils. Their approach seemed ideal for what our intent is here.
 * @param columnFamily column family from which to extract the visibility or to execute an expression against
 * @param columnQualifier column qualifier from which to extract the visibility or to execute an expression against
 * @param flowFile flow file being written
 * @param context process context
 * @return
 */
public static String produceVisibility(String columnFamily, String columnQualifier, FlowFile flowFile, ProcessContext context) {
    if (org.apache.commons.lang3.StringUtils.isNotEmpty(columnFamily)) {
        return null;
    }
    String lookupKey = String.format("visibility.%s%s%s", columnFamily, !org.apache.commons.lang3.StringUtils.isNotEmpty(columnQualifier) ? "." : "", columnQualifier);
    String fromAttribute = flowFile.getAttribute(lookupKey);

    if (fromAttribute == null && !org.apache.commons.lang3.StringUtils.isBlank(columnQualifier)) {
        String lookupKeyFam = String.format("visibility.%s", columnFamily);
        fromAttribute = flowFile.getAttribute(lookupKeyFam);
    }

    if (fromAttribute != null) {
        return fromAttribute;
    } else {
        PropertyValue descriptor = context.getProperty(lookupKey);
        if (descriptor == null || !descriptor.isSet()) {
            descriptor = context.getProperty(String.format("visibility.%s", columnFamily));
        }

        String retVal = descriptor != null ? descriptor.evaluateAttributeExpressions(flowFile).getValue() : null;

        return retVal;
    }
}
 
Example 4
Source File: ShellUserGroupProvider.java    From nifi with Apache License 2.0 6 votes vote down vote up
private int getTimeoutProperty(AuthorizerConfigurationContext authContext, String propertyName, String defaultValue) {
    final PropertyValue timeoutProperty = authContext.getProperty(propertyName);

    final String propertyValue;
    if (timeoutProperty.isSet()) {
        propertyValue = timeoutProperty.getValue();
    } else {
        propertyValue = defaultValue;
    }

    final long timeoutValue;
    try {
        timeoutValue = Math.round(FormatUtils.getPreciseTimeDuration(propertyValue, TimeUnit.SECONDS));
    } catch (final IllegalArgumentException ignored) {
        throw new AuthorizerCreationException(String.format("The %s '%s' is not a valid time interval.", propertyName, propertyValue));
    }

    return Math.toIntExact(timeoutValue);
}
 
Example 5
Source File: StandardManagedAuthorizer.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Override
public void onConfigured(AuthorizerConfigurationContext configurationContext) throws AuthorizerCreationException {
    final PropertyValue accessPolicyProviderKey = configurationContext.getProperty("Access Policy Provider");
    if (!accessPolicyProviderKey.isSet()) {
        throw new AuthorizerCreationException("The Access Policy Provider must be set.");
    }

    accessPolicyProvider = accessPolicyProviderLookup.getAccessPolicyProvider(accessPolicyProviderKey.getValue());

    // ensure the desired access policy provider was found
    if (accessPolicyProvider == null) {
        throw new AuthorizerCreationException(String.format("Unable to locate configured Access Policy Provider: %s", accessPolicyProviderKey));
    }

    userGroupProvider = accessPolicyProvider.getUserGroupProvider();

    // ensure the desired access policy provider has a user group provider
    if (userGroupProvider == null) {
        throw new AuthorizerCreationException(String.format("Configured Access Policy Provider %s does not contain a User Group Provider", accessPolicyProviderKey));
    }
}
 
Example 6
Source File: RecordBinManager.java    From nifi with Apache License 2.0 6 votes vote down vote up
private RecordBinThresholds createThresholds(FlowFile flowfile) {
    int minRecords = context.getProperty(MergeRecord.MIN_RECORDS).evaluateAttributeExpressions().asInteger();
    final int maxRecords = context.getProperty(MergeRecord.MAX_RECORDS).evaluateAttributeExpressions().asInteger();
    final long minBytes = context.getProperty(MergeRecord.MIN_SIZE).asDataSize(DataUnit.B).longValue();

    final PropertyValue maxSizeValue = context.getProperty(MergeRecord.MAX_SIZE);
    final long maxBytes = maxSizeValue.isSet() ? maxSizeValue.asDataSize(DataUnit.B).longValue() : Long.MAX_VALUE;

    final PropertyValue maxMillisValue = context.getProperty(MergeRecord.MAX_BIN_AGE);
    final String maxBinAge = maxMillisValue.getValue();
    final long maxBinMillis = maxMillisValue.isSet() ? maxMillisValue.asTimePeriod(TimeUnit.MILLISECONDS) : Long.MAX_VALUE;

    final String fragmentCountAttribute;
    final String mergeStrategy = context.getProperty(MergeRecord.MERGE_STRATEGY).getValue();
    if (MergeRecord.MERGE_STRATEGY_DEFRAGMENT.getValue().equals(mergeStrategy)) {
        fragmentCountAttribute = MergeContent.FRAGMENT_COUNT_ATTRIBUTE;
        // We don't know minRecords in defragment mode.
        minRecords = Integer.MAX_VALUE;
    } else {
        fragmentCountAttribute = null;
    }

    return new RecordBinThresholds(minRecords, maxRecords, minBytes, maxBytes, maxBinMillis, maxBinAge, fragmentCountAttribute);
}
 
Example 7
Source File: GenerateTableFetch.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Override
protected Collection<ValidationResult> customValidate(ValidationContext validationContext) {
    List<ValidationResult> results = new ArrayList<>(super.customValidate(validationContext));
    final PropertyValue columnForPartitioning = validationContext.getProperty(COLUMN_FOR_VALUE_PARTITIONING);
    // If no EL is present, ensure it's a single column (i.e. no commas in the property value)
    if (columnForPartitioning.isSet() && !columnForPartitioning.isExpressionLanguagePresent() && columnForPartitioning.getValue().contains(",")) {
        results.add(new ValidationResult.Builder().valid(false).explanation(
                COLUMN_FOR_VALUE_PARTITIONING.getDisplayName() + " requires a single column name, but a comma was detected").build());
    }

    return results;
}
 
Example 8
Source File: ShellUserGroupProvider.java    From nifi with Apache License 2.0 5 votes vote down vote up
private String getProperty(AuthorizerConfigurationContext authContext, String propertyName, String defaultValue) {
    final PropertyValue property = authContext.getProperty(propertyName);
    final String value;

    if (property != null && property.isSet()) {
        value = property.getValue();
    } else {
        value = defaultValue;
    }
    return value;

}
 
Example 9
Source File: PutHDFS.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Override
protected void preProcessConfiguration(final Configuration config, final ProcessContext context) {
    // Set umask once, to avoid thread safety issues doing it in onTrigger
    final PropertyValue umaskProp = context.getProperty(UMASK);
    final short dfsUmask;
    if (umaskProp.isSet()) {
        dfsUmask = Short.parseShort(umaskProp.getValue(), 8);
    } else {
        dfsUmask = FsPermission.getUMask(config).toShort();
    }
    FsPermission.setUMask(config, new FsPermission(dfsUmask));
}
 
Example 10
Source File: AbstractJMSProcessor.java    From nifi with Apache License 2.0 5 votes vote down vote up
private void validateLocalConnectionFactoryConfig(List<PropertyDescriptor> localConnectionFactoryProperties, PropertyDescriptor indicatorProperty, List<ValidationResult> results) {
    for (PropertyDescriptor propertyDescriptor : localConnectionFactoryProperties) {
        if (propertyDescriptor.isRequired()) {
            PropertyValue propertyValue = validationContext.getProperty(propertyDescriptor);
            if (!propertyValue.isSet()) {
                results.add(new ValidationResult.Builder()
                        .subject("Connection Factory config")
                        .valid(false)
                        .explanation(String.format("'%s' must be specified when '%s' has been configured.", propertyDescriptor.getDisplayName(), indicatorProperty.getDisplayName()))
                        .build());
            }
        }
    }
}
 
Example 11
Source File: AbstractJMSProcessor.java    From nifi with Apache License 2.0 5 votes vote down vote up
private boolean hasLocalConnectionFactoryConfig(List<PropertyDescriptor> localConnectionFactoryProperties) {
    for (PropertyDescriptor propertyDescriptor : localConnectionFactoryProperties) {
        PropertyValue propertyValue = validationContext.getProperty(propertyDescriptor);
        if (propertyValue.isSet()) {
            return true;
        }
    }
    return false;
}
 
Example 12
Source File: TransformXml.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Override
protected Collection<ValidationResult> customValidate(ValidationContext validationContext) {
    final List<ValidationResult> results = new ArrayList<>(super.customValidate(validationContext));

    PropertyValue filename = validationContext.getProperty(XSLT_FILE_NAME);
    PropertyValue controller = validationContext.getProperty(XSLT_CONTROLLER);
    PropertyValue key = validationContext.getProperty(XSLT_CONTROLLER_KEY);

    if((filename.isSet() && controller.isSet())
            || (!filename.isSet() && !controller.isSet())) {
        results.add(new ValidationResult.Builder()
                .valid(false)
                .subject(this.getClass().getSimpleName())
                .explanation("Exactly one of the \"XSLT file name\" and \"XSLT controller\" properties must be defined.")
                .build());
    }

    if(controller.isSet() && !key.isSet()) {
        results.add(new ValidationResult.Builder()
                .valid(false)
                .subject(XSLT_CONTROLLER_KEY.getDisplayName())
                .explanation("If using \"XSLT controller\", the XSLT controller key property must be defined.")
                .build());
    }

    if(controller.isSet()) {
        final LookupService<String> lookupService = validationContext.getProperty(XSLT_CONTROLLER).asControllerService(StringLookupService.class);
        final Set<String> requiredKeys = lookupService.getRequiredKeys();
        if (requiredKeys == null || requiredKeys.size() != 1) {
            results.add(new ValidationResult.Builder()
                    .valid(false)
                    .subject(XSLT_CONTROLLER.getDisplayName())
                    .explanation("This processor requires a key-value lookup service supporting exactly one required key, was: " +
                        (requiredKeys == null ? "null" : String.valueOf(requiredKeys.size())))
                    .build());
        }
    }

    return results;
}
 
Example 13
Source File: StandardSSLContextService.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
private void verifySslConfig(final ValidationContext validationContext) throws ProcessException {
    final String protocol = validationContext.getProperty(SSL_ALGORITHM).getValue();
    try {
        final PropertyValue keyPasswdProp = validationContext.getProperty(KEY_PASSWORD);
        final char[] keyPassword = keyPasswdProp.isSet() ? keyPasswdProp.getValue().toCharArray() : null;

        final String keystoreFile = validationContext.getProperty(KEYSTORE).getValue();
        if (keystoreFile == null) {
            SslContextFactory.createTrustSslContext(
                    validationContext.getProperty(TRUSTSTORE).getValue(),
                    validationContext.getProperty(TRUSTSTORE_PASSWORD).getValue().toCharArray(),
                    validationContext.getProperty(TRUSTSTORE_TYPE).getValue(),
                    protocol);
            return;
        }
        final String truststoreFile = validationContext.getProperty(TRUSTSTORE).getValue();
        if (truststoreFile == null) {
            SslContextFactory.createSslContext(
                    validationContext.getProperty(KEYSTORE).getValue(),
                    validationContext.getProperty(KEYSTORE_PASSWORD).getValue().toCharArray(),
                    keyPassword,
                    validationContext.getProperty(KEYSTORE_TYPE).getValue(),
                    protocol);
            return;
        }

        SslContextFactory.createSslContext(
                validationContext.getProperty(KEYSTORE).getValue(),
                validationContext.getProperty(KEYSTORE_PASSWORD).getValue().toCharArray(),
                keyPassword,
                validationContext.getProperty(KEYSTORE_TYPE).getValue(),
                validationContext.getProperty(TRUSTSTORE).getValue(),
                validationContext.getProperty(TRUSTSTORE_PASSWORD).getValue().toCharArray(),
                validationContext.getProperty(TRUSTSTORE_TYPE).getValue(),
                org.apache.nifi.security.util.SslContextFactory.ClientAuth.REQUIRED,
                protocol);
    } catch (final Exception e) {
        throw new ProcessException(e);
    }
}
 
Example 14
Source File: LdapUserGroupProvider.java    From nifi with Apache License 2.0 5 votes vote down vote up
private void setTimeout(final AuthorizerConfigurationContext configurationContext,
                        final Map<String, Object> baseEnvironment,
                        final String configurationProperty,
                        final String environmentKey) {

    final PropertyValue rawTimeout = configurationContext.getProperty(configurationProperty);
    if (rawTimeout.isSet()) {
        try {
            final Long timeout = FormatUtils.getTimeDuration(rawTimeout.getValue(), TimeUnit.MILLISECONDS);
            baseEnvironment.put(environmentKey, timeout.toString());
        } catch (final IllegalArgumentException iae) {
            throw new AuthorizerCreationException(String.format("The %s '%s' is not a valid time duration", configurationProperty, rawTimeout));
        }
    }
}
 
Example 15
Source File: PutHDFS.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
@OnScheduled
public void onScheduled(ProcessContext context) throws Exception {
    super.abstractOnScheduled(context);

    // Set umask once, to avoid thread safety issues doing it in onTrigger
    final PropertyValue umaskProp = context.getProperty(UMASK);
    final short dfsUmask;
    if (umaskProp.isSet()) {
        dfsUmask = Short.parseShort(umaskProp.getValue(), 8);
    } else {
        dfsUmask = FsPermission.DEFAULT_UMASK;
    }
    final Configuration conf = getConfiguration();
    FsPermission.setUMask(conf, new FsPermission(dfsUmask));
}
 
Example 16
Source File: CSVUtils.java    From nifi with Apache License 2.0 4 votes vote down vote up
private static CSVFormat buildCustomFormat(final PropertyContext context, final Map<String, String> variables) {
    final Character valueSeparator = getCharUnescapedJava(context, VALUE_SEPARATOR, variables);
    CSVFormat format = CSVFormat.newFormat(valueSeparator)
        .withAllowMissingColumnNames()
        .withIgnoreEmptyLines();

    final PropertyValue firstLineIsHeaderPropertyValue = context.getProperty(FIRST_LINE_IS_HEADER);
    if (firstLineIsHeaderPropertyValue.getValue() != null && firstLineIsHeaderPropertyValue.asBoolean()) {
        format = format.withFirstRecordAsHeader();
    }

    final Character quoteChar = getCharUnescaped(context, QUOTE_CHAR, variables);
    format = format.withQuote(quoteChar);

    final Character escapeChar = getCharUnescaped(context, ESCAPE_CHAR, variables);
    format = format.withEscape(escapeChar);

    format = format.withTrim(context.getProperty(TRIM_FIELDS).asBoolean());

    if (context.getProperty(COMMENT_MARKER).isSet()) {
        final Character commentMarker = getCharUnescaped(context, COMMENT_MARKER, variables);
        if (commentMarker != null) {
            format = format.withCommentMarker(commentMarker);
        }
    }
    if (context.getProperty(NULL_STRING).isSet()) {
        format = format.withNullString(unescape(context.getProperty(NULL_STRING).getValue()));
    }

    final PropertyValue quoteValue = context.getProperty(QUOTE_MODE);
    if (quoteValue != null && quoteValue.isSet()) {
        final QuoteMode quoteMode = QuoteMode.valueOf(quoteValue.getValue());
        format = format.withQuoteMode(quoteMode);
    }

    final PropertyValue trailingDelimiterValue = context.getProperty(TRAILING_DELIMITER);
    if (trailingDelimiterValue != null && trailingDelimiterValue.isSet()) {
        final boolean trailingDelimiter = trailingDelimiterValue.asBoolean();
        format = format.withTrailingDelimiter(trailingDelimiter);
    }

    final PropertyValue recordSeparator = context.getProperty(RECORD_SEPARATOR);
    if (recordSeparator != null && recordSeparator.isSet()) {
        final String separator = unescape(recordSeparator.getValue());
        format = format.withRecordSeparator(separator);
    }

    return format;
}
 
Example 17
Source File: AbstractMQTTProcessor.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
protected void buildClient(ProcessContext context){
    try {
        broker = context.getProperty(PROP_BROKER_URI).getValue();
        clientID = context.getProperty(PROP_CLIENTID).getValue();

        connOpts = new MqttConnectOptions();
        connOpts.setCleanSession(context.getProperty(PROP_CLEAN_SESSION).asBoolean());
        connOpts.setKeepAliveInterval(context.getProperty(PROP_KEEP_ALIVE_INTERVAL).asInteger());
        connOpts.setMqttVersion(context.getProperty(PROP_MQTT_VERSION).asInteger());
        connOpts.setConnectionTimeout(context.getProperty(PROP_CONN_TIMEOUT).asInteger());

        PropertyValue sslProp = context.getProperty(PROP_SSL_CONTEXT_SERVICE);
        if (sslProp.isSet()) {
            Properties sslProps = transformSSLContextService((SSLContextService) sslProp.asControllerService());
            connOpts.setSSLProperties(sslProps);
        }

        PropertyValue lastWillTopicProp = context.getProperty(PROP_LAST_WILL_TOPIC);
        if (lastWillTopicProp.isSet()){
            String lastWillMessage = context.getProperty(PROP_LAST_WILL_MESSAGE).getValue();
            PropertyValue lastWillRetain = context.getProperty(PROP_LAST_WILL_RETAIN);
            Integer lastWillQOS = context.getProperty(PROP_LAST_WILL_QOS).asInteger();
            connOpts.setWill(lastWillTopicProp.getValue(), lastWillMessage.getBytes(), lastWillQOS, lastWillRetain.isSet() ? lastWillRetain.asBoolean() : false);
        }


        PropertyValue usernameProp = context.getProperty(PROP_USERNAME);
        if(usernameProp.isSet()) {
            connOpts.setUserName(usernameProp.getValue());
            connOpts.setPassword(context.getProperty(PROP_PASSWORD).getValue().toCharArray());
        }

        mqttClientConnectLock.writeLock().lock();
        try{
            mqttClient = getMqttClient(broker, clientID, persistence);

        } finally {
            mqttClientConnectLock.writeLock().unlock();
        }
    } catch(MqttException me) {
        logger.error("Failed to initialize the connection to the  " + me.getMessage());
    }
}
 
Example 18
Source File: StandardS3EncryptionService.java    From nifi with Apache License 2.0 4 votes vote down vote up
@Override
protected Collection<ValidationResult> customValidate(final ValidationContext validationContext) {
    Collection<ValidationResult> validationResults = new ArrayList<>();

    String encryptionStrategyName = validationContext.getProperty(ENCRYPTION_STRATEGY).getValue();
    String encryptionStrategyDisplayName = ENCRYPTION_STRATEGY_ALLOWABLE_VALUES.get(encryptionStrategyName).getDisplayName();
    PropertyValue encryptionValueProperty = validationContext.getProperty(ENCRYPTION_VALUE);
    String encryptionValue = encryptionValueProperty.evaluateAttributeExpressions().getValue();

    switch (encryptionStrategyName) {
        case STRATEGY_NAME_NONE:
        case STRATEGY_NAME_SSE_S3:
            if (encryptionValueProperty.isSet()) {
                validationResults.add(new ValidationResult.Builder()
                        .subject(ENCRYPTION_VALUE.getDisplayName())
                        .valid(false)
                        .explanation("the property cannot be specified for encryption strategy " + encryptionStrategyDisplayName)
                        .build()
                );
            }
            break;
        case STRATEGY_NAME_SSE_KMS:
        case STRATEGY_NAME_CSE_KMS:
            if (StringUtils.isEmpty(encryptionValue)) {
                validationResults.add(new ValidationResult.Builder()
                        .subject(ENCRYPTION_VALUE.getDisplayName())
                        .valid(false)
                        .explanation("a non-empty Key ID must be specified for encryption strategy " + encryptionStrategyDisplayName)
                        .build()
                );
            }
            break;
        case STRATEGY_NAME_SSE_C:
        case STRATEGY_NAME_CSE_C:
            if (StringUtils.isEmpty(encryptionValue)) {
                validationResults.add(new ValidationResult.Builder()
                        .subject(ENCRYPTION_VALUE.getDisplayName())
                        .valid(false)
                        .explanation("a non-empty Key Material must be specified for encryption strategy " + encryptionStrategyDisplayName)
                        .build()
                );
            } else {
                S3EncryptionStrategy encryptionStrategy = NAMED_STRATEGIES.get(encryptionStrategyName);
                String keyIdOrMaterial = validationContext.getProperty(ENCRYPTION_VALUE).evaluateAttributeExpressions().getValue();

                validationResults.add(encryptionStrategy.validateKey(keyIdOrMaterial));
            }
            break;
    }

    return validationResults;
}
 
Example 19
Source File: FileUserGroupProvider.java    From nifi with Apache License 2.0 4 votes vote down vote up
@Override
public void onConfigured(AuthorizerConfigurationContext configurationContext) throws AuthorizerCreationException {
    try {
        final PropertyValue tenantsPath = configurationContext.getProperty(PROP_TENANTS_FILE);
        if (StringUtils.isBlank(tenantsPath.getValue())) {
            throw new AuthorizerCreationException("The users file must be specified.");
        }

        // get the tenants file and ensure it exists
        tenantsFile = new File(tenantsPath.getValue());
        if (!tenantsFile.exists()) {
            logger.info("Creating new users file at {}", new Object[] {tenantsFile.getAbsolutePath()});
            saveTenants(new Tenants());
        }

        final File tenantsFileDirectory = tenantsFile.getAbsoluteFile().getParentFile();

        // the restore directory is optional and may be null
        final File restoreDirectory = properties.getRestoreDirectory();
        if (restoreDirectory != null) {
            // sanity check that restore directory is a directory, creating it if necessary
            FileUtils.ensureDirectoryExistAndCanAccess(restoreDirectory);

            // check that restore directory is not the same as the user's directory
            if (tenantsFileDirectory.getAbsolutePath().equals(restoreDirectory.getAbsolutePath())) {
                throw new AuthorizerCreationException(String.format("Users file directory '%s' is the same as restore directory '%s' ",
                        tenantsFileDirectory.getAbsolutePath(), restoreDirectory.getAbsolutePath()));
            }

            // the restore copy will have same file name, but reside in a different directory
            restoreTenantsFile = new File(restoreDirectory, tenantsFile.getName());

            try {
                // sync the primary copy with the restore copy
                FileUtils.syncWithRestore(tenantsFile, restoreTenantsFile, logger);
            } catch (final IOException | IllegalStateException ioe) {
                throw new AuthorizerCreationException(ioe);
            }
        }

        // extract the identity and group mappings from nifi.properties if any are provided
        identityMappings = Collections.unmodifiableList(IdentityMappingUtil.getIdentityMappings(properties));
        groupMappings = Collections.unmodifiableList(IdentityMappingUtil.getGroupMappings(properties));

        // get the value of the legacy authorized users file
        final PropertyValue legacyAuthorizedUsersProp = configurationContext.getProperty(FileAuthorizer.PROP_LEGACY_AUTHORIZED_USERS_FILE);
        legacyAuthorizedUsersFile = legacyAuthorizedUsersProp.isSet() ? legacyAuthorizedUsersProp.getValue() : null;

        // extract any node identities
        initialUserIdentities = new HashSet<>();
        for (Map.Entry<String,String> entry : configurationContext.getProperties().entrySet()) {
            Matcher matcher = INITIAL_USER_IDENTITY_PATTERN.matcher(entry.getKey());
            if (matcher.matches() && !StringUtils.isBlank(entry.getValue())) {
                initialUserIdentities.add(IdentityMappingUtil.mapIdentity(entry.getValue(), identityMappings));
            }
        }

        load();

        // if we've copied the authorizations file to a restore directory synchronize it
        if (restoreTenantsFile != null) {
            FileUtils.copyFile(tenantsFile, restoreTenantsFile, false, false, logger);
        }

        logger.info(String.format("Users/Groups file loaded at %s", new Date().toString()));
    } catch (IOException | AuthorizerCreationException | JAXBException | IllegalStateException e) {
        throw new AuthorizerCreationException(e);
    }
}
 
Example 20
Source File: StandardSSLContextService.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
@Override
public SSLContext createSSLContext(final ClientAuth clientAuth) throws ProcessException {
    final String protocol = configContext.getProperty(SSL_ALGORITHM).getValue();
    try {
        final PropertyValue keyPasswdProp = configContext.getProperty(KEY_PASSWORD);
        final char[] keyPassword = keyPasswdProp.isSet() ? keyPasswdProp.getValue().toCharArray() : null;

        final String keystoreFile = configContext.getProperty(KEYSTORE).getValue();
        if (keystoreFile == null) {
            // If keystore not specified, create SSL Context based only on trust store.
            return SslContextFactory.createTrustSslContext(
                    configContext.getProperty(TRUSTSTORE).getValue(),
                    configContext.getProperty(TRUSTSTORE_PASSWORD).getValue().toCharArray(),
                    configContext.getProperty(TRUSTSTORE_TYPE).getValue(),
                    protocol);
        }

        final String truststoreFile = configContext.getProperty(TRUSTSTORE).getValue();
        if (truststoreFile == null) {
            // If truststore not specified, create SSL Context based only on key store.
            return SslContextFactory.createSslContext(
                    configContext.getProperty(KEYSTORE).getValue(),
                    configContext.getProperty(KEYSTORE_PASSWORD).getValue().toCharArray(),
                    keyPassword,
                    configContext.getProperty(KEYSTORE_TYPE).getValue(),
                    protocol);
        }

        return SslContextFactory.createSslContext(
                configContext.getProperty(KEYSTORE).getValue(),
                configContext.getProperty(KEYSTORE_PASSWORD).getValue().toCharArray(),
                keyPassword,
                configContext.getProperty(KEYSTORE_TYPE).getValue(),
                configContext.getProperty(TRUSTSTORE).getValue(),
                configContext.getProperty(TRUSTSTORE_PASSWORD).getValue().toCharArray(),
                configContext.getProperty(TRUSTSTORE_TYPE).getValue(),
                org.apache.nifi.security.util.SslContextFactory.ClientAuth.valueOf(clientAuth.name()),
                protocol);
    } catch (final Exception e) {
        throw new ProcessException(e);
    }
}