org.apache.nifi.components.ValidationResult Java Examples

The following examples show how to use org.apache.nifi.components.ValidationResult. 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: RedisStateProvider.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Override
protected Collection<ValidationResult> customValidate(ValidationContext validationContext) {
    final List<ValidationResult> results = new ArrayList<>(RedisUtils.validate(validationContext));

    final RedisType redisType = RedisType.fromDisplayName(validationContext.getProperty(RedisUtils.REDIS_MODE).getValue());
    if (redisType != null && redisType == RedisType.CLUSTER) {
        results.add(new ValidationResult.Builder()
                .subject(RedisUtils.REDIS_MODE.getDisplayName())
                .valid(false)
                .explanation(RedisUtils.REDIS_MODE.getDisplayName()
                        + " is configured in clustered mode, and this service requires a non-clustered Redis")
                .build());
    }

    return results;
}
 
Example #2
Source File: JsonValidator.java    From scalable-ocr with Apache License 2.0 6 votes vote down vote up
@Override
public ValidationResult validate(String subject, String input, ValidationContext context) {
    try {
        JSONUtils.INSTANCE.load(input, new TypeReference<Map<String, String>>() {
        });
    } catch (IOException e) {
        return new ValidationResult.Builder()
                .subject(subject)
                .input(value)
                .valid(false)
                .explanation("Not a valid JSON map value: " + e.getMessage())
                .build();
    }
    return new ValidationResult.Builder()
            .valid(true)
            .input(value)
            .subject(subject)
            .build();
}
 
Example #3
Source File: HiveConfigurator.java    From nifi with Apache License 2.0 6 votes vote down vote up
public Collection<ValidationResult> validate(String configFiles, String principal, String keyTab, String password,
                                             AtomicReference<ValidationResources> validationResourceHolder, ComponentLog log) {

    final List<ValidationResult> problems = new ArrayList<>();
    ValidationResources resources = validationResourceHolder.get();

    // if no resources in the holder, or if the holder has different resources loaded,
    // then load the Configuration and set the new resources in the holder
    if (resources == null || !configFiles.equals(resources.getConfigResources())) {
        log.debug("Reloading validation resources");
        resources = new ValidationResources(configFiles, getConfigurationFromFiles(configFiles));
        validationResourceHolder.set(resources);
    }

    final Configuration hiveConfig = resources.getConfiguration();

    problems.addAll(KerberosProperties.validatePrincipalWithKeytabOrPassword(this.getClass().getSimpleName(), hiveConfig, principal, keyTab, password, log));

    return problems;
}
 
Example #4
Source File: MockProcessContext.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
/**
 * Updates the value of the property with the given PropertyDescriptor to
 * the specified value IF and ONLY IF the value is valid according to the
 * descriptor's validator. Otherwise, the property value is not updated. In
 * either case, the ValidationResult is returned, indicating whether or not
 * the property is valid
 *
 * @param descriptor of property to modify
 * @param value new value
 * @return result
 */
public ValidationResult setProperty(final PropertyDescriptor descriptor, final String value) {
    requireNonNull(descriptor);
    requireNonNull(value, "Cannot set property to null value; if the intent is to remove the property, call removeProperty instead");
    final PropertyDescriptor fullyPopulatedDescriptor = component.getPropertyDescriptor(descriptor.getName());

    final ValidationResult result = fullyPopulatedDescriptor.validate(value, new MockValidationContext(this, stateManager, variableRegistry));
    String oldValue = properties.put(fullyPopulatedDescriptor, value);
    if (oldValue == null) {
        oldValue = fullyPopulatedDescriptor.getDefaultValue();
    }
    if ((value == null && oldValue != null) || (value != null && !value.equals(oldValue))) {
        component.onPropertyModified(fullyPopulatedDescriptor, oldValue, value);
    }

    return result;
}
 
Example #5
Source File: MoveHDFSTest.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Test
public void testOutputDirectoryValidator() {
    MoveHDFS proc = new TestableMoveHDFS(kerberosProperties);
    TestRunner runner = TestRunners.newTestRunner(proc);
    Collection<ValidationResult> results;
    ProcessContext pc;

    results = new HashSet<>();
    runner.setProperty(MoveHDFS.INPUT_DIRECTORY_OR_FILE, "/source");
    runner.enqueue(new byte[0]);
    pc = runner.getProcessContext();
    if (pc instanceof MockProcessContext) {
        results = ((MockProcessContext) pc).validate();
    }
    Assert.assertEquals(1, results.size());
    for (ValidationResult vr : results) {
        assertTrue(vr.toString().contains("Output Directory is required"));
    }
}
 
Example #6
Source File: PutHDFS.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
static Validator createPositiveShortValidator() {
    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);
                if (shortVal <= 0) {
                    reason = "short integer must be greater than zero";
                }
            } catch (final NumberFormatException e) {
                reason = "[" + value + "] is not a valid short integer";
            }
            return new ValidationResult.Builder().subject(subject).input(value).explanation(reason).valid(reason == null)
                    .build();
        }
    };
}
 
Example #7
Source File: ListenUDP.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
@Override
protected Collection<ValidationResult> customValidate(ValidationContext validationContext) {
    final Collection<ValidationResult> result = new ArrayList<>();

    final String sendingHost = validationContext.getProperty(SENDING_HOST).getValue();
    final String sendingPort = validationContext.getProperty(SENDING_HOST_PORT).getValue();

    if (StringUtils.isBlank(sendingHost) && StringUtils.isNotBlank(sendingPort)) {
        result.add(
                new ValidationResult.Builder()
                        .subject(SENDING_HOST.getName())
                        .valid(false)
                        .explanation("Must specify Sending Host when specifying Sending Host Port")
                        .build());
    } else if (StringUtils.isBlank(sendingPort) && StringUtils.isNotBlank(sendingHost)) {
        result.add(
                new ValidationResult.Builder()
                        .subject(SENDING_HOST_PORT.getName())
                        .valid(false)
                        .explanation("Must specify Sending Host Port when specifying Sending Host")
                        .build());
    }

    return result;
}
 
Example #8
Source File: InvokeScriptedProcessor.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
/**
 * Reloads the script located at the given path
 *
 * @param scriptPath the path to the script file to be loaded
 * @return true if the script was loaded successfully; false otherwise
 */
private boolean reloadScriptFile(final String scriptPath) {
    final Collection<ValidationResult> results = new HashSet<>();

    try (final FileInputStream scriptStream = new FileInputStream(scriptPath)) {
        return reloadScript(IOUtils.toString(scriptStream, Charset.defaultCharset()));

    } catch (final Exception e) {
        final ComponentLog logger = getLogger();
        final String message = "Unable to load script: " + e;

        logger.error(message, e);
        results.add(new ValidationResult.Builder()
                .subject("ScriptValidation")
                .valid(false)
                .explanation("Unable to load script due to " + e)
                .input(scriptPath)
                .build());
    }

    // store the updated validation results
    validationResults.set(results);

    // return whether there was any issues loading the configured script
    return results.isEmpty();
}
 
Example #9
Source File: SiteToSiteUtils.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) {
    final String value = context.newPropertyValue(input).evaluateAttributeExpressions().getValue();
    try {
        SiteToSiteRestApiClient.parseClusterUrls(value);
        return new ValidationResult.Builder()
                .input(input)
                .subject(subject)
                .valid(true)
                .build();
    } catch (IllegalArgumentException ex) {
        return new ValidationResult.Builder()
                .input(input)
                .subject(subject)
                .valid(false)
                .explanation(ex.getLocalizedMessage())
                .build();
    }
}
 
Example #10
Source File: MockProcessContext.java    From nifi with Apache License 2.0 6 votes vote down vote up
/**
 * Validates the current properties, returning ValidationResults for any
 * invalid properties. All processor defined properties will be validated.
 * If they are not included in the in the purposed configuration, the
 * default value will be used.
 *
 * @return Collection of validation result objects for any invalid findings
 * only. If the collection is empty then the processor is valid. Guaranteed
 * non-null
 */
public Collection<ValidationResult> validate() {
    final List<ValidationResult> results = new ArrayList<>();
    final ValidationContext validationContext = new MockValidationContext(this, stateManager, variableRegistry);
    final Collection<ValidationResult> componentResults = component.validate(validationContext);
    results.addAll(componentResults);

    final Collection<ValidationResult> serviceResults = validateReferencedControllerServices(validationContext);
    results.addAll(serviceResults);

    // verify all controller services are enabled
    for (Map.Entry<String, ControllerServiceConfiguration> service : getControllerServices().entrySet()) {
        if (!service.getValue().isEnabled()) {
            results.add(new ValidationResult.Builder()
                    .explanation("Controller service " + service.getKey() + " for " + this.getName() + " is not enabled")
                    .valid(false)
                    .build());
        }
    }
    return results;
}
 
Example #11
Source File: ConsumeWindowsEventLog.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
@Override
protected Collection<ValidationResult> customValidate(ValidationContext validationContext) {
    // We need to check to see if the native libraries loaded properly
    List<ValidationResult> validationResults = new ArrayList<>(super.customValidate(validationContext));
    if (wEvtApiError != null) {
        validationResults.add(new ValidationResult.Builder().valid(false).subject("System Configuration")
                .explanation("NiFi failed to load wevtapi on this system.  This processor utilizes native Windows APIs and will only work on Windows. ("
                        + wEvtApiError.getMessage() + ")").build());
    }
    if (kernel32Error != null) {
        validationResults.add(new ValidationResult.Builder().valid(false).subject("System Configuration")
                .explanation("NiFi failed to load kernel32 on this system.  This processor utilizes native Windows APIs and will only work on Windows. ("
                        + kernel32Error.getMessage() + ")").build());
    }
    return validationResults;
}
 
Example #12
Source File: ListenSMTP.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
@Override
protected Collection<ValidationResult> customValidate(ValidationContext validationContext) {
    List<ValidationResult> results = new ArrayList<>();

    String clientAuth = validationContext.getProperty(CLIENT_AUTH).getValue();
    SSLContextService sslContextService = validationContext.getProperty(SSL_CONTEXT_SERVICE).asControllerService(SSLContextService.class);

    if (sslContextService != null && !StringUtils.hasText(clientAuth)) {
        results.add(new ValidationResult.Builder()
                .subject(CLIENT_AUTH.getDisplayName())
                .explanation(CLIENT_AUTH.getDisplayName() + " must be provided when using " + SSL_CONTEXT_SERVICE.getDisplayName())
                .valid(false)
                .build());
    } else if (sslContextService == null && StringUtils.hasText(clientAuth)) {
        results.add(new ValidationResult.Builder()
                .subject(SSL_CONTEXT_SERVICE.getDisplayName())
                .explanation(SSL_CONTEXT_SERVICE.getDisplayName() + " must be provided when selecting " + CLIENT_AUTH.getDisplayName())
                .valid(false)
                .build());
    }
    return results;
}
 
Example #13
Source File: GetHTTP.java    From localization_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).evaluateAttributeExpressions().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());
    }

    if (context.getProperty(PROXY_HOST).isSet() && !context.getProperty(PROXY_PORT).isSet()) {
        results.add(new ValidationResult.Builder()
                .explanation("Proxy Host was set but no Proxy Port was specified")
                .valid(false)
                .subject("Proxy server configuration")
                .build());
    }

    return results;
}
 
Example #14
Source File: DBCPValidator.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) {
    if (context.isExpressionLanguageSupported(subject) && context.isExpressionLanguagePresent(input)) {
        return new ValidationResult.Builder().subject(subject).input(input).explanation("Expression Language Present").valid(true).build();
    }

    if (input == null) {
        return new ValidationResult.Builder().subject(subject).input(input).valid(false).explanation("Time Period cannot be null").build();
    }
    if (TIME_DURATION_PATTERN.matcher(input.toLowerCase()).matches() || input.equals("-1")) {
        return new ValidationResult.Builder().subject(subject).input(input).valid(true).build();
    } else {
        return new ValidationResult.Builder()
                .subject(subject)
                .input(input)
                .valid(false)
                .explanation("Must be of format <duration> <TimeUnit> where <duration> is a "
                        + "non-negative integer and TimeUnit is a supported Time Unit, such "
                        + "as: nanos, millis, secs, mins, hrs, days")
                .build();
    }
}
 
Example #15
Source File: AbstractCredentialsStrategy.java    From 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;
    String requiredMessageFormat = "property %1$s must be set with %2$s";
    String excludedMessageFormat = "property %1$s cannot be used with %2$s";
    String failureFormat = thisIsSelectedStrategy ? requiredMessageFormat : excludedMessageFormat;
    Collection<ValidationResult> validationFailureResults = null;

    for (PropertyDescriptor requiredProperty : requiredProperties) {
        boolean requiredPropertyIsSet = validationContext.getProperty(requiredProperty).isSet();
        if (requiredPropertyIsSet != thisIsSelectedStrategy) {
            String message = String.format(failureFormat, requiredProperty.getDisplayName(),
                    primaryStrategy.getName());
            if (validationFailureResults == null) {
                validationFailureResults = new ArrayList<>();
            }
            validationFailureResults.add(new ValidationResult.Builder()
                    .subject(requiredProperty.getDisplayName())
                    .valid(false)
                    .explanation(message).build());
        }
    }

    return validationFailureResults;
}
 
Example #16
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 #17
Source File: DeleteGridFS.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Override
protected Collection<ValidationResult> customValidate(final ValidationContext validationContext) {
    ArrayList<ValidationResult> problems = new ArrayList<>();

    boolean fileName = validationContext.getProperty(FILE_NAME).isSet();
    boolean query    = validationContext.getProperty(QUERY).isSet();

    if (fileName && query) {
        problems.add(new ValidationResult.Builder()
            .valid(false)
            .explanation("File name and Query cannot be set at the same time.")
            .build()
        );
    } else if (!fileName && !query) {
        problems.add(new ValidationResult.Builder()
            .valid(false)
            .explanation("File name or Query must be set, but not both at the same time.")
            .build()
        );
    }

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

    boolean textSpecified = validationContext.getProperty(TEXT).isSet();
    boolean attachmentSpecified = validationContext.getProperties().keySet()
            .stream()
            .anyMatch(PropertyDescriptor::isDynamic);
    boolean uploadFileYes = validationContext.getProperty(UPLOAD_FLOWFILE).asBoolean();

    if (!textSpecified && !attachmentSpecified && !uploadFileYes) {
        validationResults.add(new ValidationResult.Builder()
                .subject(TEXT.getDisplayName())
                .valid(false)
                .explanation("it is required if no attachment has been specified, nor 'Upload FlowFile' has been set to 'Yes'.")
                .build());
    }

    return validationResults;
}
 
Example #19
Source File: RegexNamespaceResolver.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Override
public Collection<ValidationResult> validate(ValidationContext validationContext) {
    final List<ValidationResult> validationResults = new ArrayList<>();
    consumeConfigurations(validationContext.getAllProperties(),
            (namespacePatterns, patterns) -> {},
            (entry, e) -> {
                final ValidationResult result = new ValidationResult.Builder()
                        .subject(entry.getKey())
                        .input(entry.getValue())
                        .explanation(e.getMessage())
                        .valid(false)
                        .build();
                validationResults.add(result);
            });
    return validationResults;
}
 
Example #20
Source File: StandardValidators.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
public static Validator createListValidator(boolean trimEntries, boolean excludeEmptyEntries, Validator validator) {
    return (subject, input, context) -> {
        if (context.isExpressionLanguageSupported(subject) && context.isExpressionLanguagePresent(input)) {
            return new ValidationResult.Builder().subject(subject).input(input).explanation("Expression Language Present").valid(true).build();
        }
        try {
            if (input == null) {
                return new ValidationResult.Builder().subject(subject).input(null).explanation("List must have at least one non-empty element").valid(false).build();
            }
            final String[] list = input.split(",");
            for (String item : list) {
                String itemToValidate = trimEntries ? item.trim() : item;
                if (!isEmpty(itemToValidate) || !excludeEmptyEntries) {
                    ValidationResult result = validator.validate(subject, itemToValidate, context);
                    if (!result.isValid()) {
                        return result;
                    }
                }
            }
            return new ValidationResult.Builder().subject(subject).input(input).explanation("Valid List").valid(true).build();
        } catch (final Exception e) {
            return new ValidationResult.Builder().subject(subject).input(input).explanation("Not a valid list").valid(false).build();
        }
    };
}
 
Example #21
Source File: StandardValidators.java    From localization_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 #22
Source File: StandardValidators.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Override
public ValidationResult validate(final String subject, final String value, final ValidationContext context) {
    if (value.length() < minimum || value.length() > maximum) {
        return new ValidationResult.Builder()
                .subject(subject)
                .valid(false)
                .input(value)
                .explanation(String.format("String length invalid [min: %d, max: %d]", minimum, maximum))
                .build();
    } else {
        return new ValidationResult.Builder()
                .valid(true)
                .input(value)
                .subject(subject)
                .build();
    }
}
 
Example #23
Source File: StandardValidators.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) {
    if (context.isExpressionLanguageSupported(subject) && context.isExpressionLanguagePresent(input)) {
        return new ValidationResult.Builder().subject(subject).input(input).explanation("Expression Language Present").valid(true).build();
    }

    if (input == null) {
        return new ValidationResult.Builder().subject(subject).input(input).valid(false).explanation("Time Period cannot be null").build();
    }
    if (Pattern.compile(FormatUtils.TIME_DURATION_REGEX).matcher(input.toLowerCase()).matches()) {
        return new ValidationResult.Builder().subject(subject).input(input).valid(true).build();
    } else {
        return new ValidationResult.Builder()
                .subject(subject)
                .input(input)
                .valid(false)
                .explanation("Must be of format <duration> <TimeUnit> where <duration> is a "
                        + "non-negative integer and TimeUnit is a supported Time Unit, such "
                        + "as: nanos, millis, secs, mins, hrs, days")
                .build();
    }
}
 
Example #24
Source File: YandexTranslate.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(TRANSLATE_CONTENT).asBoolean().equals(Boolean.FALSE)) {
        boolean foundDynamic = false;
        for (final PropertyDescriptor descriptor : validationContext.getProperties().keySet()) {
            if (descriptor.isDynamic()) {
                foundDynamic = true;
                break;
            }
        }

        if (!foundDynamic) {
            results.add(new ValidationResult.Builder().subject("Text to translate").input("<none>").valid(false)
                    .explanation("Must either set 'Translate Content' to true or add at least one user-defined property").build());
        }
    }

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

    String reason = null;
    try {
        final int intVal = Integer.parseInt(value);

        if (intVal < 0) {
            reason = "value is negative";
        }
    } catch (final NumberFormatException e) {
        reason = "value is not a valid integer";
    }

    return new ValidationResult.Builder().subject(subject).input(value).explanation(reason).valid(reason == null).build();
}
 
Example #26
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 #27
Source File: StandardValidators.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
@Override
public ValidationResult validate(final String subject, final String value, final ValidationContext context) {
    if (context.isExpressionLanguageSupported(subject) && context.isExpressionLanguagePresent(value)) {
        final ResultType resultType = context.newExpressionLanguageCompiler().getResultType(value);
        if (!resultType.equals(ResultType.STRING)) {
            return new ValidationResult.Builder()
                    .subject(subject)
                    .input(value)
                    .valid(false)
                    .explanation("Expected Attribute Query to return type " + ResultType.STRING + " but query returns type " + resultType)
                    .build();
        }

        return new ValidationResult.Builder().subject(subject).input(value).explanation("Expression Language Present").valid(true).build();
    }

    String reason = null;
    try {
        if (!Charset.isSupported(value)) {
            reason = "Character Set is not supported by this JVM.";
        }
    } catch (final UnsupportedCharsetException uce) {
        reason = "Character Set is not supported by this JVM.";
    } catch (final IllegalArgumentException iae) {
        reason = "Character Set value cannot be null.";
    }

    return new ValidationResult.Builder().subject(subject).input(value).explanation(reason).valid(reason == null).build();
}
 
Example #28
Source File: TestRouteOnAttribute.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Test
public void testInvalidOnMisconfiguredProperty() {
    final RouteOnAttribute proc = new RouteOnAttribute();
    final MockProcessContext ctx = new MockProcessContext(proc);
    final ValidationResult validationResult = ctx.setProperty("RouteA", "${a:equals('b')"); // Missing closing brace
    assertFalse(validationResult.isValid());
}
 
Example #29
Source File: CSVValidators.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Override
public ValidationResult validate(final String subject, final String input, final ValidationContext context) {

    if (input == null) {
        return new ValidationResult.Builder()
                .input(input)
                .subject(subject)
                .valid(false)
                .explanation("Input is null for this property")
                .build();
    }

    if (!context.isExpressionLanguageSupported(subject) || !context.isExpressionLanguagePresent(input)) {
        final String unescaped = CSVUtils.unescape(input);
        if (unescaped.length() != 1) {
            return new ValidationResult.Builder()
                    .input(input)
                    .subject(subject)
                    .valid(false)
                    .explanation("Value must be exactly 1 character but was " + input.length() + " in length")
                    .build();
        }

        if (illegalChars.contains(unescaped)) {
            return new ValidationResult.Builder()
                    .input(input)
                    .subject(subject)
                    .valid(false)
                    .explanation(input + " is not a valid character for this property")
                    .build();
        }
    }

    return new ValidationResult.Builder()
            .input(input)
            .subject(subject)
            .valid(true)
            .build();
}
 
Example #30
Source File: ListenUDP.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
@Override
public ValidationResult validate(String subject, String input, ValidationContext context) {
    try {
        InetAddress.getByName(input);
        return new ValidationResult.Builder().subject(subject).valid(true).input(input).build();
    } catch (final UnknownHostException e) {
        return new ValidationResult.Builder().subject(subject).valid(false).input(input).explanation("Unknown host: " + e).build();
    }
}