Search in sources :

Example 16 with PropertyDescriptor

use of org.apache.nifi.components.PropertyDescriptor in project nifi by apache.

the class TestFlowController method testSynchronizeFlowWithProcessorReferencingControllerService.

@Test
public void testSynchronizeFlowWithProcessorReferencingControllerService() throws IOException {
    final FlowSynchronizer standardFlowSynchronizer = new StandardFlowSynchronizer(StringEncryptor.createEncryptor(nifiProperties), nifiProperties);
    // create a mock proposed data flow with the same auth fingerprint as the current authorizer
    final String authFingerprint = authorizer.getFingerprint();
    final DataFlow proposedDataFlow = Mockito.mock(DataFlow.class);
    when(proposedDataFlow.getAuthorizerFingerprint()).thenReturn(authFingerprint.getBytes(StandardCharsets.UTF_8));
    final File flowFile = new File("src/test/resources/conf/processor-with-cs-flow-0.7.0.xml");
    final String flow = IOUtils.toString(new FileInputStream(flowFile));
    when(proposedDataFlow.getFlow()).thenReturn(flow.getBytes(StandardCharsets.UTF_8));
    controller.synchronize(standardFlowSynchronizer, proposedDataFlow);
    // should be two controller services
    final Set<ControllerServiceNode> controllerServiceNodes = controller.getAllControllerServices();
    assertNotNull(controllerServiceNodes);
    assertEquals(1, controllerServiceNodes.size());
    // find the controller service that was moved to the root group
    final ControllerServiceNode rootGroupCs = controllerServiceNodes.stream().filter(c -> c.getProcessGroup() != null).findFirst().get();
    assertNotNull(rootGroupCs);
    // should be one processor
    final Set<ProcessorNode> processorNodes = controller.getGroup(controller.getRootGroupId()).getProcessors();
    assertNotNull(processorNodes);
    assertEquals(1, processorNodes.size());
    // verify the processor is still pointing at the controller service that got moved to the root group
    final ProcessorNode processorNode = processorNodes.stream().findFirst().get();
    final PropertyDescriptor procControllerServiceProp = processorNode.getProperties().entrySet().stream().filter(e -> e.getValue().equals(rootGroupCs.getIdentifier())).map(e -> e.getKey()).findFirst().get();
    assertNotNull(procControllerServiceProp);
}
Also used : MockPolicyBasedAuthorizer(org.apache.nifi.authorization.MockPolicyBasedAuthorizer) Bundle(org.apache.nifi.bundle.Bundle) Arrays(java.util.Arrays) ProcessorInstantiationException(org.apache.nifi.controller.exception.ProcessorInstantiationException) FlowFileEventRepository(org.apache.nifi.controller.repository.FlowFileEventRepository) ProcessGroup(org.apache.nifi.groups.ProcessGroup) BundleCoordinate(org.apache.nifi.bundle.BundleCoordinate) ProcessorConfigDTO(org.apache.nifi.web.api.dto.ProcessorConfigDTO) URL(java.net.URL) AbstractPolicyBasedAuthorizer(org.apache.nifi.authorization.AbstractPolicyBasedAuthorizer) BundleDTO(org.apache.nifi.web.api.dto.BundleDTO) ReportingTaskInstantiationException(org.apache.nifi.controller.reporting.ReportingTaskInstantiationException) PropertyDescriptor(org.apache.nifi.components.PropertyDescriptor) PositionDTO(org.apache.nifi.web.api.dto.PositionDTO) FlowSynchronizer(org.apache.nifi.controller.serialization.FlowSynchronizer) ServiceB(org.apache.nifi.controller.service.mock.ServiceB) SchedulingStrategy(org.apache.nifi.scheduling.SchedulingStrategy) After(org.junit.After) Map(java.util.Map) MockProvenanceRepository(org.apache.nifi.provenance.MockProvenanceRepository) FlowRegistryClient(org.apache.nifi.registry.flow.FlowRegistryClient) ControllerServiceDTO(org.apache.nifi.web.api.dto.ControllerServiceDTO) Set(java.util.Set) UUID(java.util.UUID) StandardCharsets(java.nio.charset.StandardCharsets) User(org.apache.nifi.authorization.User) VariableRegistry(org.apache.nifi.registry.VariableRegistry) IOUtils(org.apache.commons.io.IOUtils) Stateful(org.apache.nifi.annotation.behavior.Stateful) Assert.assertFalse(org.junit.Assert.assertFalse) DummyProcessor(org.apache.nifi.controller.service.mock.DummyProcessor) ProcessorDTO(org.apache.nifi.web.api.dto.ProcessorDTO) ExtensionManager(org.apache.nifi.nar.ExtensionManager) DummyReportingTask(org.apache.nifi.controller.service.mock.DummyReportingTask) AuditService(org.apache.nifi.admin.service.AuditService) FlowSnippetDTO(org.apache.nifi.web.api.dto.FlowSnippetDTO) Mockito.mock(org.mockito.Mockito.mock) DataFlow(org.apache.nifi.cluster.protocol.DataFlow) ControllerServiceNode(org.apache.nifi.controller.service.ControllerServiceNode) HashMap(java.util.HashMap) Group(org.apache.nifi.authorization.Group) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) LinkedHashMap(java.util.LinkedHashMap) StringEncryptor(org.apache.nifi.encrypt.StringEncryptor) Relationship(org.apache.nifi.processor.Relationship) SystemBundle(org.apache.nifi.nar.SystemBundle) LogLevel(org.apache.nifi.logging.LogLevel) LinkedHashSet(java.util.LinkedHashSet) Before(org.junit.Before) InstanceClassLoader(org.apache.nifi.nar.InstanceClassLoader) FileBasedVariableRegistry(org.apache.nifi.registry.variable.FileBasedVariableRegistry) MalformedURLException(java.net.MalformedURLException) RequestAction(org.apache.nifi.authorization.RequestAction) Assert.assertNotNull(org.junit.Assert.assertNotNull) Assert.assertTrue(org.junit.Assert.assertTrue) LogRepository(org.apache.nifi.logging.LogRepository) Test(org.junit.Test) IOException(java.io.IOException) FileUtils(org.apache.commons.io.FileUtils) FileInputStream(java.io.FileInputStream) Mockito.when(org.mockito.Mockito.when) ServiceA(org.apache.nifi.controller.service.mock.ServiceA) File(java.io.File) Assert.assertNotEquals(org.junit.Assert.assertNotEquals) TimeUnit(java.util.concurrent.TimeUnit) Mockito(org.mockito.Mockito) NiFiProperties(org.apache.nifi.util.NiFiProperties) AccessPolicy(org.apache.nifi.authorization.AccessPolicy) BulletinRepository(org.apache.nifi.reporting.BulletinRepository) Assert(org.junit.Assert) Collections(java.util.Collections) LogRepositoryFactory(org.apache.nifi.logging.LogRepositoryFactory) Assert.assertEquals(org.junit.Assert.assertEquals) InputStream(java.io.InputStream) PropertyDescriptor(org.apache.nifi.components.PropertyDescriptor) ControllerServiceNode(org.apache.nifi.controller.service.ControllerServiceNode) FlowSynchronizer(org.apache.nifi.controller.serialization.FlowSynchronizer) File(java.io.File) DataFlow(org.apache.nifi.cluster.protocol.DataFlow) FileInputStream(java.io.FileInputStream) Test(org.junit.Test)

Example 17 with PropertyDescriptor

use of org.apache.nifi.components.PropertyDescriptor in project nifi by apache.

the class CouchbaseClusterService method onConfigured.

/**
 * Establish a connection to a Couchbase cluster.
 * @param context the configuration context
 * @throws InitializationException if unable to connect a Couchbase cluster
 */
@OnEnabled
public void onConfigured(final ConfigurationContext context) throws InitializationException {
    for (PropertyDescriptor p : context.getProperties().keySet()) {
        if (p.isDynamic() && p.getName().startsWith(DYNAMIC_PROP_BUCKET_PASSWORD)) {
            String bucketName = p.getName().substring(DYNAMIC_PROP_BUCKET_PASSWORD.length());
            String password = context.getProperty(p).getValue();
            bucketPasswords.put(bucketName, password);
        }
    }
    try {
        cluster = CouchbaseCluster.fromConnectionString(context.getProperty(CONNECTION_STRING).getValue());
    } catch (CouchbaseException e) {
        throw new InitializationException(e);
    }
}
Also used : CouchbaseException(com.couchbase.client.core.CouchbaseException) PropertyDescriptor(org.apache.nifi.components.PropertyDescriptor) InitializationException(org.apache.nifi.reporting.InitializationException) OnEnabled(org.apache.nifi.annotation.lifecycle.OnEnabled)

Example 18 with PropertyDescriptor

use of org.apache.nifi.components.PropertyDescriptor in project nifi by apache.

the class ITPutS3Object method testDynamicProperty.

@Test
public void testDynamicProperty() throws IOException {
    final String DYNAMIC_ATTRIB_KEY = "fs.runTimestamp";
    final String DYNAMIC_ATTRIB_VALUE = "${now():toNumber()}";
    final PutS3Object processor = new PutS3Object();
    final TestRunner runner = TestRunners.newTestRunner(processor);
    runner.setProperty(PutS3Object.CREDENTIALS_FILE, CREDENTIALS_FILE);
    runner.setProperty(PutS3Object.REGION, REGION);
    runner.setProperty(PutS3Object.BUCKET, BUCKET_NAME);
    runner.setProperty(PutS3Object.MULTIPART_PART_SIZE, TEST_PARTSIZE_STRING);
    PropertyDescriptor testAttrib = processor.getSupportedDynamicPropertyDescriptor(DYNAMIC_ATTRIB_KEY);
    runner.setProperty(testAttrib, DYNAMIC_ATTRIB_VALUE);
    final String FILE1_NAME = "file1";
    Map<String, String> attribs = new HashMap<>();
    attribs.put(CoreAttributes.FILENAME.key(), FILE1_NAME);
    runner.enqueue("123".getBytes(), attribs);
    runner.assertValid();
    processor.getPropertyDescriptor(DYNAMIC_ATTRIB_KEY);
    runner.run();
    runner.assertAllFlowFilesTransferred(PutS3Object.REL_SUCCESS);
    final List<MockFlowFile> successFiles = runner.getFlowFilesForRelationship(PutS3Object.REL_SUCCESS);
    Assert.assertEquals(1, successFiles.size());
    MockFlowFile ff1 = successFiles.get(0);
    Long now = System.currentTimeMillis();
    String millisNow = Long.toString(now);
    String millisOneSecAgo = Long.toString(now - 1000L);
    String usermeta = ff1.getAttribute(PutS3Object.S3_USERMETA_ATTR_KEY);
    String[] usermetaLine0 = usermeta.split(System.lineSeparator())[0].split("=");
    String usermetaKey0 = usermetaLine0[0];
    String usermetaValue0 = usermetaLine0[1];
    Assert.assertEquals(DYNAMIC_ATTRIB_KEY, usermetaKey0);
    Assert.assertTrue(usermetaValue0.compareTo(millisOneSecAgo) >= 0 && usermetaValue0.compareTo(millisNow) <= 0);
}
Also used : MockFlowFile(org.apache.nifi.util.MockFlowFile) PropertyDescriptor(org.apache.nifi.components.PropertyDescriptor) HashMap(java.util.HashMap) TestRunner(org.apache.nifi.util.TestRunner) Test(org.junit.Test)

Example 19 with PropertyDescriptor

use of org.apache.nifi.components.PropertyDescriptor in project nifi by apache.

the class AbstractCredentialsStrategy method validate.

@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<ValidationResult>();
            }
            validationFailureResults.add(new ValidationResult.Builder().subject(requiredProperty.getDisplayName()).valid(false).explanation(message).build());
        }
    }
    return validationFailureResults;
}
Also used : PropertyDescriptor(org.apache.nifi.components.PropertyDescriptor) ValidationResult(org.apache.nifi.components.ValidationResult)

Example 20 with PropertyDescriptor

use of org.apache.nifi.components.PropertyDescriptor in project nifi by apache.

the class QueryElasticsearchHttp method buildRequestURL.

private URL buildRequestURL(String baseUrl, String query, String index, String type, String fields, String sort, int pageSize, int fromIndex, ProcessContext context) throws MalformedURLException {
    if (StringUtils.isEmpty(baseUrl)) {
        throw new MalformedURLException("Base URL cannot be null");
    }
    HttpUrl.Builder builder = HttpUrl.parse(baseUrl).newBuilder();
    builder.addPathSegment((StringUtils.isEmpty(index)) ? "_all" : index);
    if (!StringUtils.isEmpty(type)) {
        builder.addPathSegment(type);
    }
    builder.addPathSegment("_search");
    builder.addQueryParameter(QUERY_QUERY_PARAM, query);
    builder.addQueryParameter(SIZE_QUERY_PARAM, String.valueOf(pageSize));
    builder.addQueryParameter(FROM_QUERY_PARAM, String.valueOf(fromIndex));
    if (!StringUtils.isEmpty(fields)) {
        String trimmedFields = Stream.of(fields.split(",")).map(String::trim).collect(Collectors.joining(","));
        builder.addQueryParameter(FIELD_INCLUDE_QUERY_PARAM, trimmedFields);
    }
    if (!StringUtils.isEmpty(sort)) {
        String trimmedFields = Stream.of(sort.split(",")).map(String::trim).collect(Collectors.joining(","));
        builder.addQueryParameter(SORT_QUERY_PARAM, trimmedFields);
    }
    // Find the user-added properties and set them as query parameters on the URL
    for (Map.Entry<PropertyDescriptor, String> property : context.getProperties().entrySet()) {
        PropertyDescriptor pd = property.getKey();
        if (pd.isDynamic()) {
            if (property.getValue() != null) {
                builder.addQueryParameter(pd.getName(), context.getProperty(pd).evaluateAttributeExpressions().getValue());
            }
        }
    }
    return builder.build().url();
}
Also used : MalformedURLException(java.net.MalformedURLException) PropertyDescriptor(org.apache.nifi.components.PropertyDescriptor) HashMap(java.util.HashMap) Map(java.util.Map) HttpUrl(okhttp3.HttpUrl)

Aggregations

PropertyDescriptor (org.apache.nifi.components.PropertyDescriptor)206 HashMap (java.util.HashMap)97 Test (org.junit.Test)67 Map (java.util.Map)57 ArrayList (java.util.ArrayList)49 HashSet (java.util.HashSet)24 IOException (java.io.IOException)23 Relationship (org.apache.nifi.processor.Relationship)22 ComponentLog (org.apache.nifi.logging.ComponentLog)21 LinkedHashMap (java.util.LinkedHashMap)20 ControllerServiceNode (org.apache.nifi.controller.service.ControllerServiceNode)19 TestRunner (org.apache.nifi.util.TestRunner)19 ValidationResult (org.apache.nifi.components.ValidationResult)17 ProcessException (org.apache.nifi.processor.exception.ProcessException)17 FlowFile (org.apache.nifi.flowfile.FlowFile)16 LinkedHashSet (java.util.LinkedHashSet)15 BundleCoordinate (org.apache.nifi.bundle.BundleCoordinate)14 PropertyValue (org.apache.nifi.components.PropertyValue)14 URL (java.net.URL)13 OnScheduled (org.apache.nifi.annotation.lifecycle.OnScheduled)13