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));
}
}
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;
}
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));
}
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(), ".")));
}
}
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);
}
}
Aggregations