Search in sources :

Example 1 with RelationshipSourceOrTarget

use of org.eclipse.winery.model.tosca.RelationshipSourceOrTarget in project winery by eclipse.

the class BackendUtils method mergeTopologyTemplateAinTopologyTemplateB.

/**
 * Merges two Topology Templates and returns the mapping between the topology elements from the original Topology
 * Template and their respective clones inside the merged topology. Hereby, the staying elements must not be
 * merged.
 *
 * @param topologyTemplateA the topology to merged into <code>topologyTemplateB</code>
 * @param topologyTemplateB the target topology in which <dode>topologyTemplateA</dode> should be merged in
 * @param stayingElementIds the TEntityTemplates that must not be merged from A to B.
 * @return A mapping between the ids in the <code>topologyTemplateA</code> and their corresponding ids in
 * <code>topologyTemplateB</code>
 */
public static Map<String, String> mergeTopologyTemplateAinTopologyTemplateB(TTopologyTemplate topologyTemplateA, TTopologyTemplate topologyTemplateB, List<String> stayingElementIds) {
    Objects.requireNonNull(topologyTemplateA);
    Objects.requireNonNull(topologyTemplateB);
    TTopologyTemplate topologyTemplateToBeMerged = new TTopologyTemplate.Builder().build();
    Map<String, String> idMapping = new HashMap<>();
    Optional<Integer> shiftLeft = topologyTemplateB.getNodeTemplateOrRelationshipTemplate().stream().filter(x -> x instanceof TNodeTemplate).map(x -> (TNodeTemplate) x).max(Comparator.comparingInt(n -> ModelUtilities.getLeft(n).orElse(0))).map(n -> ModelUtilities.getLeft(n).orElse(0));
    if (Objects.nonNull(stayingElementIds)) {
        topologyTemplateA.getNodeTemplateOrRelationshipTemplate().forEach(entity -> {
            if (!stayingElementIds.contains(entity.getId())) {
                if (entity instanceof TNodeTemplate) {
                    topologyTemplateToBeMerged.addNodeTemplate((TNodeTemplate) entity);
                } else if (entity instanceof TRelationshipTemplate) {
                    topologyTemplateToBeMerged.addRelationshipTemplate((TRelationshipTemplate) entity);
                }
            }
        });
    } else {
        topologyTemplateToBeMerged.getNodeTemplateOrRelationshipTemplate().addAll(topologyTemplateA.getNodeTemplateOrRelationshipTemplate());
    }
    if (shiftLeft.isPresent()) {
        ModelUtilities.collectIdsOfExistingTopologyElements(topologyTemplateB, idMapping);
        // patch ids of reqs change them if required
        topologyTemplateToBeMerged.getNodeTemplates().stream().filter(nt -> nt.getRequirements() != null).forEach(nt -> nt.getRequirements().forEach(oldReq -> {
            TRequirement req = SerializationUtils.clone(oldReq);
            ModelUtilities.generateNewIdOfTemplate(req, idMapping);
            topologyTemplateToBeMerged.getRelationshipTemplates().stream().filter(rt -> rt.getSourceElement().getRef() instanceof TRequirement).forEach(rt -> {
                TRequirement sourceElement = (TRequirement) rt.getSourceElement().getRef();
                if (sourceElement.getId().equalsIgnoreCase(oldReq.getId())) {
                    sourceElement.setId(req.getId());
                }
            });
        }));
        // patch ids of caps change them if required
        topologyTemplateToBeMerged.getNodeTemplates().stream().filter(nt -> nt.getCapabilities() != null).forEach(nt -> nt.getCapabilities().forEach(oldCap -> {
            TCapability cap = SerializationUtils.clone(oldCap);
            ModelUtilities.generateNewIdOfTemplate(cap, idMapping);
            topologyTemplateToBeMerged.getRelationshipTemplates().stream().filter(rt -> rt.getTargetElement().getRef() instanceof TCapability).forEach(rt -> {
                TCapability targetElement = (TCapability) rt.getTargetElement().getRef();
                if (targetElement.getId().equalsIgnoreCase(oldCap.getId())) {
                    targetElement.setId(cap.getId());
                }
            });
        }));
        ArrayList<TRelationshipTemplate> newRelationships = new ArrayList<>();
        // patch the ids of templates and add them
        topologyTemplateToBeMerged.getNodeTemplateOrRelationshipTemplate().forEach(element -> {
            TEntityTemplate rtOrNt = SerializationUtils.clone(element);
            ModelUtilities.generateNewIdOfTemplate(rtOrNt, idMapping);
            if (rtOrNt instanceof TNodeTemplate) {
                int newLeft = ModelUtilities.getLeft((TNodeTemplate) rtOrNt).orElse(0) + shiftLeft.get();
                ((TNodeTemplate) rtOrNt).setX(Integer.toString(newLeft));
            } else if (rtOrNt instanceof TRelationshipTemplate) {
                newRelationships.add((TRelationshipTemplate) rtOrNt);
            }
            topologyTemplateB.getNodeTemplateOrRelationshipTemplate().add(rtOrNt);
        });
        // update references to the new elements
        newRelationships.forEach(rel -> {
            RelationshipSourceOrTarget source = rel.getSourceElement().getRef();
            RelationshipSourceOrTarget target = rel.getTargetElement().getRef();
            if (source instanceof TNodeTemplate && (stayingElementIds == null || stayingElementIds.stream().noneMatch(elementId -> elementId.equals(source.getId())))) {
                TNodeTemplate newSource = topologyTemplateB.getNodeTemplate(idMapping.get(source.getId()));
                rel.setSourceNodeTemplate(newSource);
            }
            if (target instanceof TNodeTemplate && (stayingElementIds == null || stayingElementIds.stream().noneMatch(elementId -> elementId.equals(target.getId())))) {
                TNodeTemplate newTarget = topologyTemplateB.getNodeTemplate(idMapping.get(target.getId()));
                rel.setTargetNodeTemplate(newTarget);
            }
        });
    } else {
        topologyTemplateB.getNodeTemplateOrRelationshipTemplate().addAll(topologyTemplateToBeMerged.getNodeTemplateOrRelationshipTemplate());
    }
    return idMapping;
}
Also used : BufferedInputStream(java.io.BufferedInputStream) PlansId(org.eclipse.winery.model.ids.elements.PlansId) IdUtil(org.eclipse.winery.model.ids.IdUtil) RequirementTypeId(org.eclipse.winery.model.ids.definitions.RequirementTypeId) XSImplementation(org.apache.xerces.xs.XSImplementation) OTTopologyFragmentRefinementModel(org.eclipse.winery.model.tosca.extensions.OTTopologyFragmentRefinementModel) TRelationshipTypeImplementation(org.eclipse.winery.model.tosca.TRelationshipTypeImplementation) WineryVersion(org.eclipse.winery.common.version.WineryVersion) OTComplianceRule(org.eclipse.winery.model.tosca.extensions.OTComplianceRule) Metadata(org.apache.tika.metadata.Metadata) ErrorHandler(org.xml.sax.ErrorHandler) IdNames(org.eclipse.winery.model.ids.IdNames) XSObjectList(org.apache.xerces.xs.XSObjectList) Map(java.util.Map) GenericId(org.eclipse.winery.model.ids.GenericId) Path(java.nio.file.Path) TArtifactType(org.eclipse.winery.model.tosca.TArtifactType) TDefinitions(org.eclipse.winery.model.tosca.TDefinitions) TEntityType(org.eclipse.winery.model.tosca.TEntityType) XSTerm(org.apache.xerces.xs.XSTerm) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) Constants(org.eclipse.winery.common.Constants) Set(java.util.Set) Reader(java.io.Reader) WinerysPropertiesDefinition(org.eclipse.winery.model.tosca.extensions.kvproperties.WinerysPropertiesDefinition) StandardCharsets(java.nio.charset.StandardCharsets) RelationshipTypeId(org.eclipse.winery.model.ids.definitions.RelationshipTypeId) InvocationTargetException(java.lang.reflect.InvocationTargetException) CapabilityTypeId(org.eclipse.winery.model.ids.definitions.CapabilityTypeId) FileVisitResult(java.nio.file.FileVisitResult) PropertyDefinitionKV(org.eclipse.winery.model.tosca.extensions.kvproperties.PropertyDefinitionKV) ArtifactTemplateFilesDirectoryId(org.eclipse.winery.repository.datatypes.ids.elements.ArtifactTemplateFilesDirectoryId) TCapability(org.eclipse.winery.model.tosca.TCapability) QName(javax.xml.namespace.QName) TRequirementType(org.eclipse.winery.model.tosca.TRequirementType) NonNull(org.eclipse.jdt.annotation.NonNull) GenericDirectoryId(org.eclipse.winery.repository.datatypes.ids.elements.GenericDirectoryId) ByteArrayOutputStream(java.io.ByteArrayOutputStream) RelationshipSourceOrTarget(org.eclipse.winery.model.tosca.RelationshipSourceOrTarget) TopologyFragmentRefinementModelId(org.eclipse.winery.model.ids.extensions.TopologyFragmentRefinementModelId) DirectoryId(org.eclipse.winery.repository.datatypes.ids.elements.DirectoryId) SerializationUtils(org.apache.commons.lang3.SerializationUtils) MediaType(org.apache.tika.mime.MediaType) Constructor(java.lang.reflect.Constructor) ArrayList(java.util.ArrayList) RelationshipTypeImplementationId(org.eclipse.winery.model.ids.definitions.RelationshipTypeImplementationId) LinkedHashMap(java.util.LinkedHashMap) TestRefinementModelId(org.eclipse.winery.model.ids.extensions.TestRefinementModelId) ArtifactTemplateId(org.eclipse.winery.model.ids.definitions.ArtifactTemplateId) XmlId(org.eclipse.winery.model.ids.XmlId) TCapabilityType(org.eclipse.winery.model.tosca.TCapabilityType) TArtifactReference(org.eclipse.winery.model.tosca.TArtifactReference) XsdImportManager(org.eclipse.winery.repository.backend.xsd.XsdImportManager) DefinitionsChildId(org.eclipse.winery.model.ids.definitions.DefinitionsChildId) TNodeTemplate(org.eclipse.winery.model.tosca.TNodeTemplate) ArtifactTypeId(org.eclipse.winery.model.ids.definitions.ArtifactTypeId) VisualAppearanceId(org.eclipse.winery.repository.datatypes.ids.elements.VisualAppearanceId) XSParticle(org.apache.xerces.xs.XSParticle) Files(java.nio.file.Files) StringWriter(java.io.StringWriter) JAXBElement(javax.xml.bind.JAXBElement) IOException(java.io.IOException) Detector(org.apache.tika.detect.Detector) XSSimpleType(org.apache.xerces.impl.dv.XSSimpleType) InputStreamReader(java.io.InputStreamReader) CONTINUE(java.nio.file.FileVisitResult.CONTINUE) TArtifactTemplate(org.eclipse.winery.model.tosca.TArtifactTemplate) DateUtils(org.apache.commons.lang3.time.DateUtils) EntityTypeId(org.eclipse.winery.model.ids.definitions.EntityTypeId) XSTypeDefinition(org.apache.xerces.xs.XSTypeDefinition) JAXBSupport(org.eclipse.winery.repository.JAXBSupport) DataTypeId(org.eclipse.winery.model.ids.definitions.DataTypeId) ModelUtilities(org.eclipse.winery.model.tosca.utils.ModelUtilities) XSModel(org.apache.xerces.xs.XSModel) FileSystems(java.nio.file.FileSystems) HasIdInIdOrNameField(org.eclipse.winery.model.tosca.HasIdInIdOrNameField) TNodeTypeImplementation(org.eclipse.winery.model.tosca.TNodeTypeImplementation) SortedSet(java.util.SortedSet) Date(java.util.Date) URISyntaxException(java.net.URISyntaxException) ComplianceRuleId(org.eclipse.winery.model.ids.extensions.ComplianceRuleId) LoggerFactory(org.slf4j.LoggerFactory) HasTargetNamespace(org.eclipse.winery.model.tosca.HasTargetNamespace) Namespace(org.eclipse.winery.model.ids.Namespace) TServiceTemplate(org.eclipse.winery.model.tosca.TServiceTemplate) TPolicyType(org.eclipse.winery.model.tosca.TPolicyType) ByteArrayInputStream(java.io.ByteArrayInputStream) Namespaces(org.eclipse.winery.model.tosca.constants.Namespaces) Locale(java.util.Locale) VersionSupport(org.eclipse.winery.model.version.VersionSupport) ToscaDiff(org.eclipse.winery.model.version.ToscaDiff) PathMatcher(java.nio.file.PathMatcher) TRequirement(org.eclipse.winery.model.tosca.TRequirement) Util(org.eclipse.winery.repository.common.Util) XSComplexTypeDefinition(org.apache.xerces.xs.XSComplexTypeDefinition) URI(java.net.URI) ParseException(java.text.ParseException) OTTestRefinementModel(org.eclipse.winery.model.tosca.extensions.OTTestRefinementModel) SimpleFileVisitor(java.nio.file.SimpleFileVisitor) Filename(org.eclipse.winery.repository.backend.constants.Filename) HasName(org.eclipse.winery.model.tosca.HasName) RepositoryFileReference(org.eclipse.winery.repository.common.RepositoryFileReference) Collection(java.util.Collection) TNodeType(org.eclipse.winery.model.tosca.TNodeType) AutoDetectParser(org.apache.tika.parser.AutoDetectParser) Collectors(java.util.stream.Collectors) JAXBException(javax.xml.bind.JAXBException) XSDImportId(org.eclipse.winery.model.ids.definitions.imports.XSDImportId) Objects(java.util.Objects) TInterfaceType(org.eclipse.winery.model.tosca.TInterfaceType) AdminId(org.eclipse.winery.model.ids.admin.AdminId) List(java.util.List) TExtensibleElements(org.eclipse.winery.model.tosca.TExtensibleElements) TPlan(org.eclipse.winery.model.tosca.TPlan) RepositoryCorruptException(org.eclipse.winery.repository.exceptions.RepositoryCorruptException) TDeploymentArtifact(org.eclipse.winery.model.tosca.TDeploymentArtifact) Optional(java.util.Optional) XSElementDeclaration(org.apache.xerces.xs.XSElementDeclaration) Marshaller(javax.xml.bind.Marshaller) XSImplementationImpl(org.apache.xerces.impl.xs.XSImplementationImpl) ServiceTemplateId(org.eclipse.winery.model.ids.definitions.ServiceTemplateId) TEntityTemplate(org.eclipse.winery.model.tosca.TEntityTemplate) HashMap(java.util.HashMap) XSLoader(org.apache.xerces.xs.XSLoader) TTopologyTemplate(org.eclipse.winery.model.tosca.TTopologyTemplate) HashSet(java.util.HashSet) OTPatternRefinementModel(org.eclipse.winery.model.tosca.extensions.OTPatternRefinementModel) PatternRefinementModelId(org.eclipse.winery.model.ids.extensions.PatternRefinementModelId) InterfaceTypeId(org.eclipse.winery.model.ids.definitions.InterfaceTypeId) XMLConstants(javax.xml.XMLConstants) NodeTypeImplementationId(org.eclipse.winery.model.ids.definitions.NodeTypeImplementationId) PolicyTypeId(org.eclipse.winery.model.ids.definitions.PolicyTypeId) TImport(org.eclipse.winery.model.tosca.TImport) Unmarshaller(javax.xml.bind.Unmarshaller) ToscaExportUtil(org.eclipse.winery.repository.export.ToscaExportUtil) Logger(org.slf4j.Logger) Iterator(java.util.Iterator) XSModelGroup(org.apache.xerces.xs.XSModelGroup) GitInfo(org.eclipse.winery.repository.GitInfo) PlanId(org.eclipse.winery.model.ids.elements.PlanId) TImplementationArtifact(org.eclipse.winery.model.tosca.TImplementationArtifact) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes) ToscaElementId(org.eclipse.winery.model.ids.elements.ToscaElementId) TDataType(org.eclipse.winery.model.tosca.TDataType) SAXParseException(org.xml.sax.SAXParseException) GitBasedRepository(org.eclipse.winery.repository.backend.filebased.GitBasedRepository) Element(org.w3c.dom.Element) TRelationshipType(org.eclipse.winery.model.tosca.TRelationshipType) TRelationshipTemplate(org.eclipse.winery.model.tosca.TRelationshipTemplate) LSInput(org.w3c.dom.ls.LSInput) Comparator(java.util.Comparator) PolicyTemplateId(org.eclipse.winery.model.ids.definitions.PolicyTemplateId) Collections(java.util.Collections) TPolicyTemplate(org.eclipse.winery.model.tosca.TPolicyTemplate) InputStream(java.io.InputStream) NodeTypeId(org.eclipse.winery.model.ids.definitions.NodeTypeId) LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap) TEntityTemplate(org.eclipse.winery.model.tosca.TEntityTemplate) RelationshipSourceOrTarget(org.eclipse.winery.model.tosca.RelationshipSourceOrTarget) ArrayList(java.util.ArrayList) TCapability(org.eclipse.winery.model.tosca.TCapability) TRequirement(org.eclipse.winery.model.tosca.TRequirement) TTopologyTemplate(org.eclipse.winery.model.tosca.TTopologyTemplate) TRelationshipTemplate(org.eclipse.winery.model.tosca.TRelationshipTemplate) TNodeTemplate(org.eclipse.winery.model.tosca.TNodeTemplate)

Aggregations

BufferedInputStream (java.io.BufferedInputStream)1 ByteArrayInputStream (java.io.ByteArrayInputStream)1 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 IOException (java.io.IOException)1 InputStream (java.io.InputStream)1 InputStreamReader (java.io.InputStreamReader)1 Reader (java.io.Reader)1 StringWriter (java.io.StringWriter)1 Constructor (java.lang.reflect.Constructor)1 InvocationTargetException (java.lang.reflect.InvocationTargetException)1 URI (java.net.URI)1 URISyntaxException (java.net.URISyntaxException)1 StandardCharsets (java.nio.charset.StandardCharsets)1 FileSystems (java.nio.file.FileSystems)1 FileVisitResult (java.nio.file.FileVisitResult)1 CONTINUE (java.nio.file.FileVisitResult.CONTINUE)1 Files (java.nio.file.Files)1 Path (java.nio.file.Path)1 PathMatcher (java.nio.file.PathMatcher)1 SimpleFileVisitor (java.nio.file.SimpleFileVisitor)1