Search in sources :

Example 6 with FlowSnippetDTO

use of org.apache.nifi.web.api.dto.FlowSnippetDTO in project nifi by apache.

the class TemplateSerializerTest method validateDiffWithChangingComponentIdAndAdditionalElements.

@Test
public void validateDiffWithChangingComponentIdAndAdditionalElements() throws Exception {
    // Create initial template (TemplateDTO)
    FlowSnippetDTO snippet = new FlowSnippetDTO();
    Set<ProcessorDTO> procs = new HashSet<>();
    for (int i = 4; i > 0; i--) {
        ProcessorDTO procDTO = new ProcessorDTO();
        procDTO.setType("Processor" + i + ".class");
        procDTO.setId(ComponentIdGenerator.generateId().toString());
        procs.add(procDTO);
    }
    snippet.setProcessors(procs);
    TemplateDTO origTemplate = new TemplateDTO();
    origTemplate.setDescription("MyTemplate");
    origTemplate.setId("MyTemplate");
    origTemplate.setSnippet(snippet);
    byte[] serTemplate = TemplateSerializer.serialize(origTemplate);
    // Deserialize Template into TemplateDTO
    ByteArrayInputStream in = new ByteArrayInputStream(serTemplate);
    JAXBContext context = JAXBContext.newInstance(TemplateDTO.class);
    Unmarshaller unmarshaller = context.createUnmarshaller();
    XMLStreamReader xsr = XmlUtils.createSafeReader(in);
    JAXBElement<TemplateDTO> templateElement = unmarshaller.unmarshal(xsr, TemplateDTO.class);
    TemplateDTO deserTemplate = templateElement.getValue();
    // Modify deserialized template
    FlowSnippetDTO deserSnippet = deserTemplate.getSnippet();
    Set<ProcessorDTO> deserProcs = deserSnippet.getProcessors();
    int c = 0;
    for (ProcessorDTO processorDTO : deserProcs) {
        if (c % 2 == 0) {
            processorDTO.setName("Hello-" + c);
        }
        c++;
    }
    // add new Processor
    ProcessorDTO procDTO = new ProcessorDTO();
    procDTO.setType("ProcessorNew" + ".class");
    procDTO.setId(ComponentIdGenerator.generateId().toString());
    deserProcs.add(procDTO);
    // Serialize modified template
    byte[] serTemplate2 = TemplateSerializer.serialize(deserTemplate);
    RawText rt1 = new RawText(serTemplate);
    RawText rt2 = new RawText(serTemplate2);
    EditList diffList = new EditList();
    diffList.addAll(new HistogramDiff().diff(RawTextComparator.DEFAULT, rt1, rt2));
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    try (DiffFormatter diff = new DiffFormatter(out)) {
        diff.format(diffList, rt1, rt2);
        BufferedReader reader = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(out.toByteArray()), StandardCharsets.UTF_8));
        List<String> changes = reader.lines().peek(System.out::println).filter(line -> line.startsWith("+") || line.startsWith("-")).collect(Collectors.toList());
        assertEquals("+            <name>Hello-0</name>", changes.get(0));
        assertEquals("+            <name>Hello-2</name>", changes.get(1));
        assertEquals("+        <processors>", changes.get(2));
        assertEquals("+            <type>ProcessorNew.class</type>", changes.get(4));
        assertEquals("+        </processors>", changes.get(5));
    }
}
Also used : HistogramDiff(org.eclipse.jgit.diff.HistogramDiff) XmlUtils(org.apache.nifi.security.xml.XmlUtils) ByteArrayOutputStream(java.io.ByteArrayOutputStream) RawTextComparator(org.eclipse.jgit.diff.RawTextComparator) HashSet(java.util.HashSet) ByteArrayInputStream(java.io.ByteArrayInputStream) TemplateDTO(org.apache.nifi.web.api.dto.TemplateDTO) XMLStreamReader(javax.xml.stream.XMLStreamReader) RawText(org.eclipse.jgit.diff.RawText) JAXBContext(javax.xml.bind.JAXBContext) ComponentIdGenerator(org.apache.nifi.util.ComponentIdGenerator) Unmarshaller(javax.xml.bind.Unmarshaller) EditList(org.eclipse.jgit.diff.EditList) JAXBElement(javax.xml.bind.JAXBElement) Set(java.util.Set) Test(org.junit.Test) InputStreamReader(java.io.InputStreamReader) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) List(java.util.List) DiffFormatter(org.eclipse.jgit.diff.DiffFormatter) ProcessorDTO(org.apache.nifi.web.api.dto.ProcessorDTO) BufferedReader(java.io.BufferedReader) Assert.assertEquals(org.junit.Assert.assertEquals) FlowSnippetDTO(org.apache.nifi.web.api.dto.FlowSnippetDTO) FlowSnippetDTO(org.apache.nifi.web.api.dto.FlowSnippetDTO) XMLStreamReader(javax.xml.stream.XMLStreamReader) InputStreamReader(java.io.InputStreamReader) HistogramDiff(org.eclipse.jgit.diff.HistogramDiff) TemplateDTO(org.apache.nifi.web.api.dto.TemplateDTO) JAXBContext(javax.xml.bind.JAXBContext) ByteArrayOutputStream(java.io.ByteArrayOutputStream) RawText(org.eclipse.jgit.diff.RawText) ByteArrayInputStream(java.io.ByteArrayInputStream) ProcessorDTO(org.apache.nifi.web.api.dto.ProcessorDTO) BufferedReader(java.io.BufferedReader) EditList(org.eclipse.jgit.diff.EditList) Unmarshaller(javax.xml.bind.Unmarshaller) DiffFormatter(org.eclipse.jgit.diff.DiffFormatter) HashSet(java.util.HashSet) Test(org.junit.Test)

Example 7 with FlowSnippetDTO

use of org.apache.nifi.web.api.dto.FlowSnippetDTO in project nifi by apache.

the class SnippetAuditor method copySnippetAdvice.

/**
 * Audits copy/paste.
 *
 * @param proceedingJoinPoint join point
 * @return dto
 * @throws Throwable ex
 */
@Around("within(org.apache.nifi.web.dao.SnippetDAO+) && " + "execution(org.apache.nifi.web.api.dto.FlowSnippetDTO copySnippet(java.lang.String, java.lang.String, java.lang.Double, java.lang.Double, java.lang.String))")
public FlowSnippetDTO copySnippetAdvice(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
    // perform the underlying operation
    FlowSnippetDTO snippet = (FlowSnippetDTO) proceedingJoinPoint.proceed();
    auditSnippet(snippet);
    return snippet;
}
Also used : FlowSnippetDTO(org.apache.nifi.web.api.dto.FlowSnippetDTO) Around(org.aspectj.lang.annotation.Around)

Example 8 with FlowSnippetDTO

use of org.apache.nifi.web.api.dto.FlowSnippetDTO in project nifi by apache.

the class TestFlowController method testInstantiateSnippetWithDisabledProcessor.

@Test
public void testInstantiateSnippetWithDisabledProcessor() throws ProcessorInstantiationException {
    final String id = UUID.randomUUID().toString();
    final BundleCoordinate coordinate = systemBundle.getBundleDetails().getCoordinate();
    final ProcessorNode processorNode = controller.createProcessor(DummyProcessor.class.getName(), id, coordinate);
    processorNode.disable();
    // create a processor dto
    final ProcessorDTO processorDTO = new ProcessorDTO();
    // use a different id here
    processorDTO.setId(UUID.randomUUID().toString());
    processorDTO.setPosition(new PositionDTO(new Double(0), new Double(0)));
    processorDTO.setStyle(processorNode.getStyle());
    processorDTO.setParentGroupId("1234");
    processorDTO.setInputRequirement(processorNode.getInputRequirement().name());
    processorDTO.setPersistsState(processorNode.getProcessor().getClass().isAnnotationPresent(Stateful.class));
    processorDTO.setRestricted(processorNode.isRestricted());
    processorDTO.setExtensionMissing(processorNode.isExtensionMissing());
    processorDTO.setType(processorNode.getCanonicalClassName());
    processorDTO.setBundle(new BundleDTO(coordinate.getGroup(), coordinate.getId(), coordinate.getVersion()));
    processorDTO.setName(processorNode.getName());
    processorDTO.setState(processorNode.getScheduledState().toString());
    processorDTO.setRelationships(new ArrayList<>());
    processorDTO.setDescription("description");
    processorDTO.setSupportsParallelProcessing(!processorNode.isTriggeredSerially());
    processorDTO.setSupportsEventDriven(processorNode.isEventDrivenSupported());
    processorDTO.setSupportsBatching(processorNode.isSessionBatchingSupported());
    ProcessorConfigDTO configDTO = new ProcessorConfigDTO();
    configDTO.setSchedulingPeriod(processorNode.getSchedulingPeriod());
    configDTO.setPenaltyDuration(processorNode.getPenalizationPeriod());
    configDTO.setYieldDuration(processorNode.getYieldPeriod());
    configDTO.setRunDurationMillis(processorNode.getRunDuration(TimeUnit.MILLISECONDS));
    configDTO.setConcurrentlySchedulableTaskCount(processorNode.getMaxConcurrentTasks());
    configDTO.setLossTolerant(processorNode.isLossTolerant());
    configDTO.setComments(processorNode.getComments());
    configDTO.setBulletinLevel(processorNode.getBulletinLevel().name());
    configDTO.setSchedulingStrategy(processorNode.getSchedulingStrategy().name());
    configDTO.setExecutionNode(processorNode.getExecutionNode().name());
    configDTO.setAnnotationData(processorNode.getAnnotationData());
    processorDTO.setConfig(configDTO);
    // create the snippet with the processor
    final FlowSnippetDTO flowSnippetDTO = new FlowSnippetDTO();
    flowSnippetDTO.setProcessors(Collections.singleton(processorDTO));
    // instantiate the snippet
    assertEquals(0, controller.getRootGroup().getProcessors().size());
    controller.instantiateSnippet(controller.getRootGroup(), flowSnippetDTO);
    assertEquals(1, controller.getRootGroup().getProcessors().size());
    assertTrue(controller.getRootGroup().getProcessors().iterator().next().getScheduledState().equals(ScheduledState.DISABLED));
}
Also used : Stateful(org.apache.nifi.annotation.behavior.Stateful) ProcessorConfigDTO(org.apache.nifi.web.api.dto.ProcessorConfigDTO) FlowSnippetDTO(org.apache.nifi.web.api.dto.FlowSnippetDTO) ProcessorDTO(org.apache.nifi.web.api.dto.ProcessorDTO) DummyProcessor(org.apache.nifi.controller.service.mock.DummyProcessor) BundleDTO(org.apache.nifi.web.api.dto.BundleDTO) BundleCoordinate(org.apache.nifi.bundle.BundleCoordinate) PositionDTO(org.apache.nifi.web.api.dto.PositionDTO) Test(org.junit.Test)

Example 9 with FlowSnippetDTO

use of org.apache.nifi.web.api.dto.FlowSnippetDTO in project nifi by apache.

the class StandardTemplateDAO method instantiateTemplate.

@Override
public FlowSnippetDTO instantiateTemplate(String groupId, Double originX, Double originY, String encodingVersion, FlowSnippetDTO requestSnippet, String idGenerationSeed) {
    ProcessGroup group = locateProcessGroup(flowController, groupId);
    try {
        // copy the template which pre-processes all ids
        FlowSnippetDTO snippet = snippetUtils.copy(requestSnippet, group, idGenerationSeed, false);
        // calculate scaling factors based on the template encoding version attempt to parse the encoding version.
        // get the major version, or 0 if no version could be parsed
        final FlowEncodingVersion templateEncodingVersion = FlowEncodingVersion.parse(encodingVersion);
        int templateEncodingMajorVersion = templateEncodingVersion != null ? templateEncodingVersion.getMajorVersion() : 0;
        // based on the major version < 1, use the default scaling factors.  Otherwise, don't scale (use factor of 1.0)
        double factorX = templateEncodingMajorVersion < 1 ? FlowController.DEFAULT_POSITION_SCALE_FACTOR_X : 1.0;
        double factorY = templateEncodingMajorVersion < 1 ? FlowController.DEFAULT_POSITION_SCALE_FACTOR_Y : 1.0;
        // reposition and scale the template contents
        org.apache.nifi.util.SnippetUtils.moveAndScaleSnippet(snippet, originX, originY, factorX, factorY);
        // find all the child process groups in each process group in the top level of this snippet
        final List<ProcessGroupDTO> childProcessGroups = org.apache.nifi.util.SnippetUtils.findAllProcessGroups(snippet);
        // scale (but don't reposition) child process groups
        childProcessGroups.stream().forEach(processGroup -> org.apache.nifi.util.SnippetUtils.scaleSnippet(processGroup.getContents(), factorX, factorY));
        // instantiate the template into this group
        flowController.instantiateSnippet(group, snippet);
        return snippet;
    } catch (ProcessorInstantiationException pie) {
        throw new NiFiCoreException(String.format("Unable to instantiate template because processor type '%s' is unknown to this NiFi.", StringUtils.substringAfterLast(pie.getMessage(), ".")));
    }
}
Also used : FlowSnippetDTO(org.apache.nifi.web.api.dto.FlowSnippetDTO) NiFiCoreException(org.apache.nifi.web.NiFiCoreException) ProcessGroup(org.apache.nifi.groups.ProcessGroup) ProcessorInstantiationException(org.apache.nifi.controller.exception.ProcessorInstantiationException) ProcessGroupDTO(org.apache.nifi.web.api.dto.ProcessGroupDTO) FlowEncodingVersion(org.apache.nifi.controller.serialization.FlowEncodingVersion)

Example 10 with FlowSnippetDTO

use of org.apache.nifi.web.api.dto.FlowSnippetDTO in project nifi by apache.

the class SnippetUtils method addControllerServices.

/**
 * Finds all Controller Services that are referenced in the given Process Group (and child Process Groups, recursively), and
 * adds them to the given servicesByGroup map
 *
 * @param group the Process Group to start from
 * @param dto the DTO representation of the Process Group
 * @param allServicesReferenced a Set of all Controller Service DTO's that have already been referenced; used to dedupe services
 * @param contentsByGroup a Map of Process Group ID to the Process Group's contents
 * @param highestGroupId the UUID of the 'highest' process group in the snippet
 */
private void addControllerServices(final ProcessGroup group, final ProcessGroupDTO dto, final Set<ControllerServiceDTO> allServicesReferenced, final boolean includeControllerServices, final Set<String> visitedGroupIds, final Map<String, FlowSnippetDTO> contentsByGroup, final String highestGroupId) {
    final FlowSnippetDTO contents = dto.getContents();
    contentsByGroup.put(dto.getId(), contents);
    if (contents == null) {
        return;
    }
    // include this group in the ancestry for this snippet, services only get included if the includeControllerServices
    // flag is set or if the service is defined within this groups hierarchy within the snippet
    visitedGroupIds.add(group.getIdentifier());
    for (final ProcessorNode procNode : group.getProcessors()) {
        // Include all referenced services that are not already included in this snippet.
        getControllerServices(procNode.getProperties()).stream().filter(svc -> allServicesReferenced.add(svc)).filter(svc -> includeControllerServices || visitedGroupIds.contains(svc.getParentGroupId())).forEach(svc -> {
            final String svcGroupId = svc.getParentGroupId();
            final String destinationGroupId = contentsByGroup.containsKey(svcGroupId) ? svcGroupId : highestGroupId;
            svc.setParentGroupId(destinationGroupId);
            final FlowSnippetDTO snippetDto = contentsByGroup.get(destinationGroupId);
            if (snippetDto != null) {
                Set<ControllerServiceDTO> services = snippetDto.getControllerServices();
                if (services == null) {
                    snippetDto.setControllerServices(Collections.singleton(svc));
                } else {
                    services.add(svc);
                    snippetDto.setControllerServices(services);
                }
            }
        });
    }
    // Map child process group ID to the child process group for easy lookup
    final Map<String, ProcessGroupDTO> childGroupMap = contents.getProcessGroups().stream().collect(Collectors.toMap(childGroupDto -> childGroupDto.getId(), childGroupDto -> childGroupDto));
    for (final ProcessGroup childGroup : group.getProcessGroups()) {
        final ProcessGroupDTO childDto = childGroupMap.get(childGroup.getIdentifier());
        if (childDto == null) {
            continue;
        }
        addControllerServices(childGroup, childDto, allServicesReferenced, includeControllerServices, visitedGroupIds, contentsByGroup, highestGroupId);
    }
}
Also used : RemoteProcessGroupContentsDTO(org.apache.nifi.web.api.dto.RemoteProcessGroupContentsDTO) ProcessGroup(org.apache.nifi.groups.ProcessGroup) ProcessorConfigDTO(org.apache.nifi.web.api.dto.ProcessorConfigDTO) ConnectableType(org.apache.nifi.connectable.ConnectableType) LoggerFactory(org.slf4j.LoggerFactory) Port(org.apache.nifi.connectable.Port) ConnectionDTO(org.apache.nifi.web.api.dto.ConnectionDTO) StringUtils(org.apache.commons.lang3.StringUtils) PropertyDescriptor(org.apache.nifi.components.PropertyDescriptor) ResourceType(org.apache.nifi.authorization.resource.ResourceType) PositionDTO(org.apache.nifi.web.api.dto.PositionDTO) SecureRandom(java.security.SecureRandom) LabelDTO(org.apache.nifi.web.api.dto.LabelDTO) ProcessGroupDTO(org.apache.nifi.web.api.dto.ProcessGroupDTO) PropertyDescriptorDTO(org.apache.nifi.web.api.dto.PropertyDescriptorDTO) TenantEntity(org.apache.nifi.web.api.entity.TenantEntity) Map(java.util.Map) Connection(org.apache.nifi.connectable.Connection) FunnelDTO(org.apache.nifi.web.api.dto.FunnelDTO) ComponentIdGenerator(org.apache.nifi.util.ComponentIdGenerator) Label(org.apache.nifi.controller.label.Label) ControllerServiceDTO(org.apache.nifi.web.api.dto.ControllerServiceDTO) AccessPolicyDAO(org.apache.nifi.web.dao.AccessPolicyDAO) Collection(java.util.Collection) Set(java.util.Set) UUID(java.util.UUID) RemoteProcessGroupPortDTO(org.apache.nifi.web.api.dto.RemoteProcessGroupPortDTO) Snippet(org.apache.nifi.controller.Snippet) Collectors(java.util.stream.Collectors) ResourceFactory(org.apache.nifi.authorization.resource.ResourceFactory) FlowController(org.apache.nifi.controller.FlowController) StandardCharsets(java.nio.charset.StandardCharsets) PortDTO(org.apache.nifi.web.api.dto.PortDTO) List(java.util.List) ScheduledState(org.apache.nifi.controller.ScheduledState) RemoteProcessGroup(org.apache.nifi.groups.RemoteProcessGroup) ProcessorDTO(org.apache.nifi.web.api.dto.ProcessorDTO) Entry(java.util.Map.Entry) ControllerServiceState(org.apache.nifi.controller.service.ControllerServiceState) DtoFactory(org.apache.nifi.web.api.dto.DtoFactory) Resource(org.apache.nifi.authorization.Resource) FlowSnippetDTO(org.apache.nifi.web.api.dto.FlowSnippetDTO) RemoteProcessGroupDTO(org.apache.nifi.web.api.dto.RemoteProcessGroupDTO) ProcessorNode(org.apache.nifi.controller.ProcessorNode) Funnel(org.apache.nifi.connectable.Funnel) ControllerServiceNode(org.apache.nifi.controller.service.ControllerServiceNode) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) AccessPolicyDTO(org.apache.nifi.web.api.dto.AccessPolicyDTO) LinkedHashSet(java.util.LinkedHashSet) Logger(org.slf4j.Logger) RequestAction(org.apache.nifi.authorization.RequestAction) ComponentDTO(org.apache.nifi.web.api.dto.ComponentDTO) AccessPolicy(org.apache.nifi.authorization.AccessPolicy) Collections(java.util.Collections) ConnectableDTO(org.apache.nifi.web.api.dto.ConnectableDTO) FlowSnippetDTO(org.apache.nifi.web.api.dto.FlowSnippetDTO) ControllerServiceDTO(org.apache.nifi.web.api.dto.ControllerServiceDTO) ProcessorNode(org.apache.nifi.controller.ProcessorNode) ProcessGroup(org.apache.nifi.groups.ProcessGroup) RemoteProcessGroup(org.apache.nifi.groups.RemoteProcessGroup) ProcessGroupDTO(org.apache.nifi.web.api.dto.ProcessGroupDTO) RemoteProcessGroupDTO(org.apache.nifi.web.api.dto.RemoteProcessGroupDTO)

Aggregations

FlowSnippetDTO (org.apache.nifi.web.api.dto.FlowSnippetDTO)30 ProcessGroupDTO (org.apache.nifi.web.api.dto.ProcessGroupDTO)15 ProcessorDTO (org.apache.nifi.web.api.dto.ProcessorDTO)15 ConnectionDTO (org.apache.nifi.web.api.dto.ConnectionDTO)10 HashMap (java.util.HashMap)9 ControllerServiceDTO (org.apache.nifi.web.api.dto.ControllerServiceDTO)9 ProcessorConfigDTO (org.apache.nifi.web.api.dto.ProcessorConfigDTO)9 HashSet (java.util.HashSet)8 PortDTO (org.apache.nifi.web.api.dto.PortDTO)8 RemoteProcessGroupDTO (org.apache.nifi.web.api.dto.RemoteProcessGroupDTO)8 ArrayList (java.util.ArrayList)7 List (java.util.List)7 Set (java.util.Set)7 Collectors (java.util.stream.Collectors)7 BundleCoordinate (org.apache.nifi.bundle.BundleCoordinate)7 PositionDTO (org.apache.nifi.web.api.dto.PositionDTO)7 Test (org.junit.Test)7 Map (java.util.Map)6 ProcessGroup (org.apache.nifi.groups.ProcessGroup)6 RemoteProcessGroupPortDTO (org.apache.nifi.web.api.dto.RemoteProcessGroupPortDTO)6