org.apache.nifi.components.ValidationContext Java Examples

The following examples show how to use org.apache.nifi.components.ValidationContext. 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: DistributeLoad.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
@Override
public ValidationResult validate(String subject, String input, ValidationContext context) {
    ValidationResult result = new ValidationResult.Builder().subject(subject).valid(true).input(input).explanation("Good FQDNs").build();
    if (null == input) {
        result = new ValidationResult.Builder().subject(subject).input(input).valid(false)
        .explanation("Need to specify delimited list of FQDNs").build();
        return result;
    }
    String[] hostNames = input.split("(?:,+|;+|\\s+)");
    for (String hostName : hostNames) {
        if (StringUtils.isNotBlank(hostName) && !hostName.contains(".")) {
            result = new ValidationResult.Builder().subject(subject).input(input).valid(false)
            .explanation("Need a FQDN rather than a simple host name.").build();
            return result;
        }
    }
    return result;
}
 
Example #2
Source File: StandardProcessorTestRunner.java    From localization_nifi with 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 #3
Source File: GetHDFS.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Override
protected Collection<ValidationResult> customValidate(ValidationContext context) {
    final List<ValidationResult> problems = new ArrayList<>(super.customValidate(context));

    final Long minAgeProp = context.getProperty(MIN_AGE).asTimePeriod(TimeUnit.MILLISECONDS);
    final Long maxAgeProp = context.getProperty(MAX_AGE).asTimePeriod(TimeUnit.MILLISECONDS);
    final long minimumAge = (minAgeProp == null) ? 0L : minAgeProp;
    final long maximumAge = (maxAgeProp == null) ? Long.MAX_VALUE : maxAgeProp;
    if (minimumAge > maximumAge) {
        problems.add(new ValidationResult.Builder().valid(false).subject("GetHDFS Configuration")
                .explanation(MIN_AGE.getName() + " cannot be greater than " + MAX_AGE.getName()).build());
    }

    try {
        new Path(context.getProperty(DIRECTORY).evaluateAttributeExpressions().getValue());
    } catch (Exception e) {
        problems.add(new ValidationResult.Builder()
                .valid(false)
                .subject("Directory")
                .explanation(e.getMessage())
                .build());
    }

    return problems;
}
 
Example #4
Source File: GetAzureQueueStorage.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Override
public Collection<ValidationResult> customValidate(final ValidationContext validationContext) {
    final List<ValidationResult> problems = new ArrayList<>(super.customValidate(validationContext));
    final int visibilityTimeout = validationContext.getProperty(VISIBILITY_TIMEOUT).asTimePeriod(TimeUnit.SECONDS).intValue();

    if (visibilityTimeout <= 0) {
        problems.add(new ValidationResult.Builder()
                                         .valid(false)
                                         .subject(VISIBILITY_TIMEOUT.getDisplayName())
                                         .explanation(VISIBILITY_TIMEOUT.getDisplayName() + " should be greater than 0 secs")
                                         .build());
    }

    AzureStorageUtils.validateProxySpec(validationContext, problems);

    return problems;
}
 
Example #5
Source File: ConsumeMQTT.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Override
public Collection<ValidationResult> customValidate(ValidationContext context) {
    final Collection<ValidationResult> results = super.customValidate(context);
    int newSize = context.getProperty(PROP_MAX_QUEUE_SIZE).asInteger();
    if (mqttQueue == null) {
        mqttQueue = new LinkedBlockingQueue<>(context.getProperty(PROP_MAX_QUEUE_SIZE).asInteger());
    }
    int msgPending = mqttQueue.size();
    if (msgPending > newSize) {
        results.add(new ValidationResult.Builder()
                .valid(false)
                .subject("ConsumeMQTT Configuration")
                .explanation(String.format("%s (%d) is smaller than the number of messages pending (%d).",
                        PROP_MAX_QUEUE_SIZE.getDisplayName(), newSize, msgPending))
                .build());
    }

    final boolean clientIDSet = context.getProperty(PROP_CLIENTID).isSet();
    final boolean groupIDSet = context.getProperty(PROP_GROUPID).isSet();
    if (clientIDSet && groupIDSet) {
        results.add(new ValidationResult.Builder().subject("Client ID and Group ID").valid(false).explanation("if client ID is not unique, multiple nodes cannot join the consumer group").build());
    }

    return results;
}
 
Example #6
Source File: ConsumeMQTT.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
@Override
public Collection<ValidationResult> customValidate(ValidationContext context) {
    final Collection<ValidationResult> results = super.customValidate(context);
    int newSize = context.getProperty(PROP_MAX_QUEUE_SIZE).asInteger();
    if (mqttQueue == null) {
        mqttQueue = new LinkedBlockingQueue<>(context.getProperty(PROP_MAX_QUEUE_SIZE).asInteger());
    }
    int msgPending = mqttQueue.size();
    if (msgPending > newSize) {
        results.add(new ValidationResult.Builder()
                .valid(false)
                .subject("ConsumeMQTT Configuration")
                .explanation(String.format("%s (%d) is smaller than the number of messages pending (%d).",
                        PROP_MAX_QUEUE_SIZE.getDisplayName(), newSize, msgPending))
                .build());
    }

    return results;
}
 
Example #7
Source File: DebugFlow.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
@Override
public ValidationResult validate(final String subject, final String input, final ValidationContext context) {
    final ValidationResult.Builder resultBuilder = new ValidationResult.Builder()
        .subject(subject)
        .input(input);

    try {
        final Class<?> exceptionClass = Class.forName(input);
        if (RuntimeException.class.isAssignableFrom(exceptionClass)) {
            resultBuilder.valid(true);
        } else {
            resultBuilder.valid(false).explanation("Class " + input + " is a Checked Exception, not a RuntimeException");
        }
    } catch (ClassNotFoundException e) {
        resultBuilder.valid(false).explanation("Class " + input + " cannot be found");
    }

    return resultBuilder.build();
}
 
Example #8
Source File: SimpleDateFormatValidator.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Override
public ValidationResult validate(final String subject, final String input, final ValidationContext context) {
    try {
        new SimpleDateFormat(input);
    } catch (final Exception e) {
        return new ValidationResult.Builder()
            .input(input)
            .subject(subject)
            .valid(false)
            .explanation("Invalid Date format: " + e.getMessage())
            .build();
    }

    return new ValidationResult.Builder()
        .input(input)
        .subject(subject)
        .valid(true)
        .build();
}
 
Example #9
Source File: PostHTTP.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Override
protected Collection<ValidationResult> customValidate(final ValidationContext context) {
    final Collection<ValidationResult> results = new ArrayList<>();

    if (context.getProperty(URL).getValue().startsWith("https") && context.getProperty(SSL_CONTEXT_SERVICE).getValue() == null) {
        results.add(new ValidationResult.Builder()
                .explanation("URL is set to HTTPS protocol but no SSLContext has been specified")
                .valid(false).subject("SSL Context").build());
    }

    boolean sendAsFlowFile = context.getProperty(SEND_AS_FLOWFILE).asBoolean();
    int compressionLevel = context.getProperty(COMPRESSION_LEVEL).asInteger();
    boolean chunkedSet = context.getProperty(CHUNKED_ENCODING).isSet();

    if (compressionLevel == 0 && !sendAsFlowFile && !chunkedSet) {
        results.add(new ValidationResult.Builder().valid(false).subject(CHUNKED_ENCODING.getName())
                .explanation("if compression level is 0 and not sending as a FlowFile, then the \'" + CHUNKED_ENCODING.getName() + "\' property must be set").build());
    }

    HTTPUtils.validateProxyProperties(context, results);

    return results;
}
 
Example #10
Source File: PutCloudWatchMetric.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
@Override
public ValidationResult validate(String subject, String input, ValidationContext context) {
    if (context.isExpressionLanguageSupported(subject) && context.isExpressionLanguagePresent(input)) {
        return (new ValidationResult.Builder()).subject(subject).input(input).explanation("Expression Language Present").valid(true).build();
    } else {
        String reason = null;

        try {
            Double.parseDouble(input);
        } catch (NumberFormatException e) {
            reason = "not a valid Double";
        }

        return (new ValidationResult.Builder()).subject(subject).input(input).explanation(reason).valid(reason == null).build();
    }
}
 
Example #11
Source File: TestStandardValidators.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Test
public void testURIListValidator() {
    Validator val = StandardValidators.URI_LIST_VALIDATOR;
    ValidationContext vc = mock(ValidationContext.class);
    ValidationResult vr = val.validate("foo", null, vc);
    assertFalse(vr.isValid());

    vr = val.validate("foo", "", vc);
    assertFalse(vr.isValid());

    vr = val.validate("foo", "/no_scheme", vc);
    assertTrue(vr.isValid());

    vr = val.validate("foo", "http://localhost 8080, https://host2:8080 ", vc);
    assertFalse(vr.isValid());

    vr = val.validate("foo", "http://localhost , https://host2:8080 ", vc);
    assertTrue(vr.isValid());
}
 
Example #12
Source File: ListenSyslog.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
@Override
protected Collection<ValidationResult> customValidate(final ValidationContext validationContext) {
    final List<ValidationResult> results = new ArrayList<>();
    if (validationContext.getProperty(MAX_BATCH_SIZE).asInteger() > 1 && validationContext.getProperty(PARSE_MESSAGES).asBoolean()) {
        results.add(new ValidationResult.Builder().subject("Parse Messages").input("true").valid(false)
            .explanation("Cannot set Parse Messages to 'true' if Batch Size is greater than 1").build());
    }

    final String protocol = validationContext.getProperty(PROTOCOL).getValue();
    final SSLContextService sslContextService = validationContext.getProperty(SSL_CONTEXT_SERVICE).asControllerService(SSLContextService.class);

    if (UDP_VALUE.getValue().equals(protocol) && sslContextService != null) {
        results.add(new ValidationResult.Builder()
                .explanation("SSL can not be used with UDP")
                .valid(false).subject("SSL Context").build());
    }

    return results;
}
 
Example #13
Source File: TestProcessorLifecycle.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
@Override
protected List<PropertyDescriptor> getSupportedPropertyDescriptors() {
    PropertyDescriptor PROP = new PropertyDescriptor.Builder()
            .name("P")
            .description("Blah Blah")
            .required(true)
            .addValidator(new Validator() {
                @Override
                public ValidationResult validate(final String subject, final String value, final ValidationContext context) {
                    return new ValidationResult.Builder().subject(subject).input(value).valid(value != null && !value.isEmpty()).explanation(subject + " cannot be empty").build();
                }
            })
            .build();

    PropertyDescriptor SERVICE = new PropertyDescriptor.Builder()
            .name("S")
            .description("Blah Blah")
            .required(true)
            .identifiesControllerService(ITestservice.class)
            .build();

    return this.withService ? Arrays.asList(new PropertyDescriptor[]{PROP, SERVICE})
            : Arrays.asList(new PropertyDescriptor[]{PROP});
}
 
Example #14
Source File: UpdateAttribute.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
@Override
public ValidationResult validate(String subject, String input, ValidationContext context) {
    if (context.isExpressionLanguageSupported(subject) && context.isExpressionLanguagePresent(input)) {
        final AttributeExpression.ResultType resultType = context.newExpressionLanguageCompiler().getResultType(input);
        if (!resultType.equals(AttributeExpression.ResultType.STRING)) {
            return new ValidationResult.Builder()
                    .subject(subject)
                    .input(input)
                    .valid(false)
                    .explanation("Expected property to to return type " + AttributeExpression.ResultType.STRING +
                            " but expression returns type " + resultType)
                    .build();
        }
        return new ValidationResult.Builder()
                .subject(subject)
                .input(input)
                .valid(true)
                .explanation("Property returns type " + AttributeExpression.ResultType.STRING)
                .build();
    }

    return DPV_RE_VALIDATOR.validate(subject, input, context);
}
 
Example #15
Source File: GetHDFSFileInfo.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Override
protected Collection<ValidationResult> customValidate(ValidationContext validationContext) {
    final List<ValidationResult> validationResults = new ArrayList<>(super.customValidate(validationContext));

    String destination = validationContext.getProperty(DESTINATION).getValue();
    String grouping = validationContext.getProperty(GROUPING).getValue();
    String batchSize = validationContext.getProperty(BATCH_SIZE).getValue();

    if (
        (!DESTINATION_CONTENT.getValue().equals(destination) || !GROUP_NONE.getValue().equals(grouping))
            && batchSize != null
    ) {
        validationResults.add(new ValidationResult.Builder()
            .valid(false)
            .subject(BATCH_SIZE.getDisplayName())
            .explanation("'" + BATCH_SIZE.getDisplayName() + "' is applicable only when " +
                "'" + DESTINATION.getDisplayName() + "'='" + DESTINATION_CONTENT.getDisplayName() + "' and " +
                "'" + GROUPING.getDisplayName() + "'='" + GROUP_NONE.getDisplayName() + "'")
            .build());
    }

    return validationResults;
}
 
Example #16
Source File: AbstractKiteProcessor.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
@Override
public ValidationResult validate(String subject, String uri, ValidationContext context) {
    String message = "not set";
    boolean isValid = true;

    if (uri.trim().isEmpty()) {
        isValid = false;
    } else {
        final boolean elPresent = context.isExpressionLanguageSupported(subject) && context.isExpressionLanguagePresent(uri);
        if (!elPresent) {
            try {
                new URIBuilder(URI.create(uri)).build();
            } catch (RuntimeException e) {
                message = e.getMessage();
                isValid = false;
            }
        }
    }

    return new ValidationResult.Builder()
            .subject(subject)
            .input(uri)
            .explanation("Dataset URI is invalid: " + message)
            .valid(isValid)
            .build();
}
 
Example #17
Source File: JsonValidator.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Override
public ValidationResult validate(String subject, String input, ValidationContext context) {
    ObjectMapper mapper = new ObjectMapper();
    if (context.isExpressionLanguageSupported(subject) && context.isExpressionLanguagePresent(input)) {
        return new ValidationResult.Builder().subject(subject).input(input).explanation("Expression Language Present").valid(true).build();
    }

    try {
        Class clz = input.startsWith("[") ? List.class : Map.class;
        mapper.readValue(input, clz);
    } catch (Exception e) {
        return new ValidationResult.Builder().subject(subject).input(input).valid(false)
                .explanation(subject + " is not a valid JSON representation due to " + e.getLocalizedMessage())
                .build();
    }

    return new ValidationResult.Builder().subject(subject).input(input).valid(true).build();
}
 
Example #18
Source File: GetHBase.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
@Override
protected Collection<ValidationResult> customValidate(ValidationContext validationContext) {
    final String columns = validationContext.getProperty(COLUMNS).getValue();
    final String filter = validationContext.getProperty(FILTER_EXPRESSION).getValue();

    final List<ValidationResult> problems = new ArrayList<>();

    if (!StringUtils.isBlank(columns) && !StringUtils.isBlank(filter)) {
        problems.add(new ValidationResult.Builder()
                .subject(FILTER_EXPRESSION.getDisplayName())
                .input(filter).valid(false)
                .explanation("a filter expression can not be used in conjunction with the Columns property")
                .build());
    }

    return problems;
}
 
Example #19
Source File: StandardValidators.java    From nifi with Apache License 2.0 6 votes vote down vote up
private static Validator createURLValidator() {
    return new Validator() {
        @Override
        public ValidationResult validate(final String subject, final String input, final ValidationContext context) {
            if (context.isExpressionLanguageSupported(subject) && context.isExpressionLanguagePresent(input)) {
                return new ValidationResult.Builder().subject(subject).input(input).explanation("Expression Language Present").valid(true).build();
            }

            try {
                final String evaluatedInput = context.newPropertyValue(input).evaluateAttributeExpressions().getValue();
                new URL(evaluatedInput);
                return new ValidationResult.Builder().subject(subject).input(input).explanation("Valid URL").valid(true).build();
            } catch (final Exception e) {
                return new ValidationResult.Builder().subject(subject).input(input).explanation("Not a valid URL").valid(false).build();
            }
        }
    };
}
 
Example #20
Source File: ConsumeJMS.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Override
protected Collection<ValidationResult> customValidate(ValidationContext validationContext) {
    final List<ValidationResult> validationResults = new ArrayList<>(super.customValidate(validationContext));

    String destinationType = validationContext.getProperty(DESTINATION_TYPE).getValue();
    String errorQueue = validationContext.getProperty(ERROR_QUEUE).getValue();

    if (errorQueue != null && !QUEUE.equals(destinationType)) {
        validationResults.add(new ValidationResult.Builder()
            .valid(false)
            .subject(ERROR_QUEUE.getDisplayName())
            .explanation("'" + ERROR_QUEUE.getDisplayName() + "' is applicable only when " +
                "'" + DESTINATION_TYPE.getDisplayName() + "'='" + QUEUE + "'")
            .build());
    }
    return validationResults;
}
 
Example #21
Source File: StatelessControllerServiceLookup.java    From nifi with Apache License 2.0 6 votes vote down vote up
public ValidationResult setControllerServiceProperty(final ControllerService service, final PropertyDescriptor property, final StatelessProcessContext context,
                                                     final VariableRegistry registry, final String value) {
    final StatelessStateManager serviceStateManager = controllerServiceStateManagers.get(service.getIdentifier());
    if (serviceStateManager == null) {
        throw new IllegalStateException("Controller service " + service + " has not been added to this TestRunner via the #addControllerService method");
    }

    final ValidationContext validationContext = new StatelessValidationContext(context, this, serviceStateManager, registry, parameterContext);
    final ValidationResult validationResult = property.validate(value, validationContext);

    final StatelessControllerServiceConfiguration configuration = getControllerServiceConfigToUpdate(service);
    final PropertyConfiguration oldValue = configuration.getProperties().get(property);
    final PropertyConfiguration propertyConfiguration = createPropertyConfiguration(value, property.isExpressionLanguageSupported());
    configuration.setProperty(property, propertyConfiguration);

    if (oldValue == null && value != null) {
        service.onPropertyModified(property, null, value);
    } else if ((value == null && oldValue.getRawValue() != null) || (value != null && !value.equals(oldValue.getRawValue()))) {
        service.onPropertyModified(property, oldValue.getRawValue(), value);
    }

    return validationResult;
}
 
Example #22
Source File: StandardValidators.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
public static Validator createDataSizeBoundsValidator(final long minBytesInclusive, final long maxBytesInclusive) {
    return new Validator() {

        @Override
        public ValidationResult validate(final String subject, final String input, final ValidationContext context) {
            if (context.isExpressionLanguageSupported(subject) && context.isExpressionLanguagePresent(input)) {
                return new ValidationResult.Builder().subject(subject).input(input).explanation("Expression Language Present").valid(true).build();
            }

            final ValidationResult vr = DATA_SIZE_VALIDATOR.validate(subject, input, context);
            if (!vr.isValid()) {
                return vr;
            }
            final long dataSizeBytes = DataUnit.parseDataSize(input, DataUnit.B).longValue();
            if (dataSizeBytes < minBytesInclusive) {
                return new ValidationResult.Builder().subject(subject).input(input).valid(false).explanation("Cannot be smaller than " + minBytesInclusive + " bytes").build();
            }
            if (dataSizeBytes > maxBytesInclusive) {
                return new ValidationResult.Builder().subject(subject).input(input).valid(false).explanation("Cannot be larger than " + maxBytesInclusive + " bytes").build();
            }
            return new ValidationResult.Builder().subject(subject).input(input).valid(true).build();
        }
    };

}
 
Example #23
Source File: FetchS3Object.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Override
protected Collection<ValidationResult> customValidate(ValidationContext validationContext) {
    final List<ValidationResult> problems = new ArrayList<>(super.customValidate(validationContext));

    AmazonS3EncryptionService encryptionService = validationContext.getProperty(ENCRYPTION_SERVICE).asControllerService(AmazonS3EncryptionService.class);
    if (encryptionService != null) {
        String strategyName = encryptionService.getStrategyName();
        if (strategyName.equals(AmazonS3EncryptionService.STRATEGY_NAME_SSE_S3) || strategyName.equals(AmazonS3EncryptionService.STRATEGY_NAME_SSE_KMS)) {
            problems.add(new ValidationResult.Builder()
                    .subject(ENCRYPTION_SERVICE.getDisplayName())
                    .valid(false)
                    .explanation(encryptionService.getStrategyDisplayName() + " is not a valid encryption strategy for fetching objects. Decryption will be handled automatically " +
                            "during the fetch of S3 objects encrypted with " + encryptionService.getStrategyDisplayName())
                    .build()
            );
        }
    }

    return problems;
}
 
Example #24
Source File: AbstractFlumeProcessor.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
protected static Validator createSourceValidator() {
    return new Validator() {
        @Override
        public ValidationResult validate(final String subject, final String value, final ValidationContext context) {
            String reason = null;
            try {
                ExecuteFlumeSource.SOURCE_FACTORY.create("NiFi Source", value);
            } catch (Exception ex) {
                reason = ex.getLocalizedMessage();
                reason = Character.toLowerCase(reason.charAt(0)) + reason.substring(1);
            }
            return new ValidationResult.Builder().subject(subject)
                .input(value)
                .explanation(reason)
                .valid(reason == null)
                .build();
        }
    };
}
 
Example #25
Source File: AbstractFlumeProcessor.java    From nifi with Apache License 2.0 6 votes vote down vote up
protected static Validator createSourceValidator() {
    return new Validator() {
        @Override
        public ValidationResult validate(final String subject, final String value, final ValidationContext context) {
            String reason = null;
            try {
                ExecuteFlumeSource.SOURCE_FACTORY.create("NiFi Source", value);
            } catch (Exception ex) {
                reason = ex.getLocalizedMessage();
                reason = Character.toLowerCase(reason.charAt(0)) + reason.substring(1);
            }
            return new ValidationResult.Builder().subject(subject)
                .input(value)
                .explanation(reason)
                .valid(reason == null)
                .build();
        }
    };
}
 
Example #26
Source File: PutHDFS.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
static Validator createUmaskValidator() {
    return new Validator() {
        @Override
        public ValidationResult validate(final String subject, final String value, final ValidationContext context) {
            String reason = null;
            try {
                final short shortVal = Short.parseShort(value, 8);
                if (shortVal < 0) {
                    reason = "octal umask [" + value + "] cannot be negative";
                } else if (shortVal > 511) {
                    // HDFS umask has 9 bits: rwxrwxrwx ; the sticky bit cannot be umasked
                    reason = "octal umask [" + value + "] is not a valid umask";
                }
            } catch (final NumberFormatException e) {
                reason = "[" + value + "] is not a valid short octal number";
            }
            return new ValidationResult.Builder().subject(subject).input(value).explanation(reason).valid(reason == null)
                    .build();
        }
    };
}
 
Example #27
Source File: AbstractBooleanCredentialsStrategy.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
@Override
public Collection<ValidationResult> validate(final ValidationContext validationContext,
                                             final CredentialsStrategy primaryStrategy) {
    boolean thisIsSelectedStrategy = this == primaryStrategy;
    Boolean useStrategy = validationContext.getProperty(strategyProperty).asBoolean();
    if (!thisIsSelectedStrategy && (useStrategy == null ? false : useStrategy)) {
        String failureFormat = "property %1$s cannot be used with %2$s";
        Collection<ValidationResult> validationFailureResults = new ArrayList<ValidationResult>();
        String message = String.format(failureFormat, strategyProperty.getDisplayName(),
                primaryStrategy.getName());
        validationFailureResults.add(new ValidationResult.Builder()
                .subject(strategyProperty.getDisplayName())
                .valid(false)
                .explanation(message).build());
        return  validationFailureResults;
    }
    return null;
}
 
Example #28
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 #29
Source File: PutCassandraRecord.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Override
protected Collection<ValidationResult> customValidate(ValidationContext validationContext) {
    Set<ValidationResult> results = (Set<ValidationResult>) super.customValidate(validationContext);

    String statementType = validationContext.getProperty(STATEMENT_TYPE).getValue();

    if (UPDATE_TYPE.getValue().equalsIgnoreCase(statementType)) {
        // Check that update keys are set
        String updateKeys = validationContext.getProperty(UPDATE_KEYS).getValue();
        if (StringUtils.isEmpty(updateKeys)) {
            results.add(new ValidationResult.Builder().subject("Update statement configuration").valid(false).explanation(
                    "if the Statement Type is set to Update, then the Update Keys must be specified as well").build());
        }

        // Check that if the update method is set to increment or decrement that the batch statement type is set to
        // unlogged or counter (or USE_ATTR_TYPE, which we cannot check at this point).
        String updateMethod = validationContext.getProperty(UPDATE_METHOD).getValue();
        String batchStatementType = validationContext.getProperty(BATCH_STATEMENT_TYPE).getValue();
        if (INCR_TYPE.getValue().equalsIgnoreCase(updateMethod)
                || DECR_TYPE.getValue().equalsIgnoreCase(updateMethod)) {
            if (!(COUNTER_TYPE.getValue().equalsIgnoreCase(batchStatementType)
                    || UNLOGGED_TYPE.getValue().equalsIgnoreCase(batchStatementType)
                    || BATCH_STATEMENT_TYPE_USE_ATTR_TYPE.getValue().equalsIgnoreCase(batchStatementType))) {
                results.add(new ValidationResult.Builder().subject("Update method configuration").valid(false).explanation(
                        "if the Update Method is set to Increment or Decrement, then the Batch Statement Type must be set " +
                                "to either COUNTER or UNLOGGED").build());
            }
        }
    }

    return results;
}
 
Example #30
Source File: TestStandardValidators.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateURLorFileValidator() {
    Validator val = StandardValidators.createURLorFileValidator();
    ValidationResult vr;

    final ValidationContext validationContext = Mockito.mock(ValidationContext.class);

    vr = val.validate("URLorFile", null, validationContext);
    assertFalse(vr.isValid());

    vr = val.validate("URLorFile", "", validationContext);
    assertFalse(vr.isValid());

    vr = val.validate("URLorFile", "http://nifi.apache.org", validationContext);
    assertTrue(vr.isValid());

    vr = val.validate("URLorFile", "http//nifi.apache.org", validationContext);
    assertFalse(vr.isValid());

    vr = val.validate("URLorFile", "nifi.apache.org", validationContext);
    assertFalse(vr.isValid());

    vr = val.validate("URLorFile", "src/test/resources/this_file_exists.txt", validationContext);
    assertTrue(vr.isValid());

    vr = val.validate("URLorFile", "src/test/resources/this_file_does_not_exist.txt", validationContext);
    assertFalse(vr.isValid());

}