Search in sources :

Example 1 with TEntityTemplate

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

the class IGenericRepository method getReferencedDefinitionsChildIds.

default Collection<DefinitionsChildId> getReferencedDefinitionsChildIds(ComplianceRuleId id) {
    // We have to use a HashSet to ensure that no duplicate ids are added
    // E.g., there may be multiple relationship templates having the same type
    Collection<DefinitionsChildId> ids = new HashSet<>();
    TComplianceRule complianceRule = this.getElement(id);
    // TODO extend to required Structure
    if (complianceRule.getIdentifier() != null) {
        for (TEntityTemplate entityTemplate : complianceRule.getIdentifier().getNodeTemplateOrRelationshipTemplate()) {
            QName qname = entityTemplate.getType();
            if (entityTemplate instanceof TNodeTemplate) {
                ids.add(new NodeTypeId(qname));
                TNodeTemplate n = (TNodeTemplate) entityTemplate;
                // crawl through deployment artifacts
                TDeploymentArtifacts deploymentArtifacts = n.getDeploymentArtifacts();
                if (deploymentArtifacts != null) {
                    List<TDeploymentArtifact> das = deploymentArtifacts.getDeploymentArtifact();
                    for (TDeploymentArtifact da : das) {
                        ids.add(new ArtifactTypeId(da.getArtifactType()));
                        if ((qname = da.getArtifactRef()) != null) {
                            ids.add(new ArtifactTemplateId(qname));
                        }
                    }
                }
                // crawl through reqs/caps
                TNodeTemplate.Requirements requirements = n.getRequirements();
                if (requirements != null) {
                    for (TRequirement req : requirements.getRequirement()) {
                        QName type = req.getType();
                        RequirementTypeId rtId = new RequirementTypeId(type);
                        ids.add(rtId);
                    }
                }
                TNodeTemplate.Capabilities capabilities = n.getCapabilities();
                if (capabilities != null) {
                    for (TCapability cap : capabilities.getCapability()) {
                        QName type = cap.getType();
                        CapabilityTypeId ctId = new CapabilityTypeId(type);
                        ids.add(ctId);
                    }
                }
                // crawl through policies
                org.eclipse.winery.model.tosca.TNodeTemplate.Policies policies = n.getPolicies();
                if (policies != null) {
                    for (TPolicy pol : policies.getPolicy()) {
                        QName type = pol.getPolicyType();
                        PolicyTypeId ctId = new PolicyTypeId(type);
                        ids.add(ctId);
                    }
                }
            } else {
                assert (entityTemplate instanceof TRelationshipTemplate);
                ids.add(new RelationshipTypeId(qname));
            }
        }
    }
    return ids;
}
Also used : DefinitionsChildId(org.eclipse.winery.common.ids.definitions.DefinitionsChildId) ArtifactTypeId(org.eclipse.winery.common.ids.definitions.ArtifactTypeId) TRequirement(org.eclipse.winery.model.tosca.TRequirement) TComplianceRule(org.eclipse.winery.model.tosca.TComplianceRule) TRelationshipTemplate(org.eclipse.winery.model.tosca.TRelationshipTemplate) TDeploymentArtifact(org.eclipse.winery.model.tosca.TDeploymentArtifact) TNodeTemplate(org.eclipse.winery.model.tosca.TNodeTemplate) HashSet(java.util.HashSet) RelationshipTypeId(org.eclipse.winery.common.ids.definitions.RelationshipTypeId) TEntityTemplate(org.eclipse.winery.model.tosca.TEntityTemplate) CapabilityTypeId(org.eclipse.winery.common.ids.definitions.CapabilityTypeId) QName(javax.xml.namespace.QName) TCapability(org.eclipse.winery.model.tosca.TCapability) ArtifactTemplateId(org.eclipse.winery.common.ids.definitions.ArtifactTemplateId) TDeploymentArtifacts(org.eclipse.winery.model.tosca.TDeploymentArtifacts) PolicyTypeId(org.eclipse.winery.common.ids.definitions.PolicyTypeId) RequirementTypeId(org.eclipse.winery.common.ids.definitions.RequirementTypeId) TPolicy(org.eclipse.winery.model.tosca.TPolicy) NodeTypeId(org.eclipse.winery.common.ids.definitions.NodeTypeId)

Example 2 with TEntityTemplate

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

the class TopologyTemplateResource method computeDi.

@POST
@Path("kvcomparison")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public PropertyDiffList computeDi(UpdateInfo updateInfo) {
    List<String> resolvedProperties = new ArrayList<>();
    List<String> removedProperties = new ArrayList<>();
    List<String> newProperties = new ArrayList<>();
    Optional<TEntityTemplate> foundTemplate = topologyTemplate.getNodeTemplateOrRelationshipTemplate().stream().filter(template -> template.getId().equals(updateInfo.getNodeTemplateId())).filter(template -> template.getProperties() != null).findFirst();
    if (foundTemplate.isPresent() && Objects.nonNull(foundTemplate.get().getProperties()) && Objects.nonNull(ModelUtilities.getPropertiesKV(foundTemplate.get()))) {
        HashMap<String, String> oldKvs = ModelUtilities.getPropertiesKV(foundTemplate.get());
        QName qNameType = QName.valueOf(updateInfo.getNewComponentType());
        IRepository repository = RepositoryFactory.getRepository();
        TEntityType newNodeTypeVersion = repository.getElement(new NodeTypeId(qNameType));
        if (Objects.nonNull(newNodeTypeVersion) && Objects.nonNull(newNodeTypeVersion.getWinerysPropertiesDefinition())) {
            List<PropertyDefinitionKV> newKvs = newNodeTypeVersion.getWinerysPropertiesDefinition().getPropertyDefinitions();
            resolvedProperties = newKvs.stream().map(PropertyDefinitionKV::getKey).filter(keys -> oldKvs.keySet().stream().map(String::toLowerCase).collect(Collectors.toList()).contains(keys.toLowerCase())).collect(Collectors.toList());
            removedProperties = oldKvs.keySet().stream().filter(keys -> !newKvs.stream().map(newProp -> newProp.getKey().toLowerCase()).collect(Collectors.toList()).contains(keys.toLowerCase())).collect(Collectors.toList());
            newProperties = newKvs.stream().map(PropertyDefinitionKV::getKey).filter(keys -> !oldKvs.keySet().stream().map(String::toLowerCase).collect(Collectors.toList()).contains(keys.toLowerCase())).collect(Collectors.toList());
        }
    }
    return new PropertyDiffList(resolvedProperties, removedProperties, newProperties);
}
Also used : UpdateInfo(org.eclipse.winery.repository.rest.resources.apiData.UpdateInfo) Produces(javax.ws.rs.Produces) Path(javax.ws.rs.Path) LoggerFactory(org.slf4j.LoggerFactory) ApiParam(io.swagger.annotations.ApiParam) NamespaceProperties(org.eclipse.winery.repository.backend.filebased.NamespaceProperties) AvailableFeaturesApiData(org.eclipse.winery.repository.rest.resources.apiData.AvailableFeaturesApiData) EncodingUtil(org.eclipse.winery.model.ids.EncodingUtil) WineryVersion(org.eclipse.winery.common.version.WineryVersion) ApiOperation(io.swagger.annotations.ApiOperation) MediaType(javax.ws.rs.core.MediaType) QueryParam(javax.ws.rs.QueryParam) InvalidParameterException(java.security.InvalidParameterException) Consumes(javax.ws.rs.Consumes) SolutionStrategy(org.eclipse.winery.model.adaptation.problemsolving.SolutionStrategy) VersionSupport(org.eclipse.winery.model.version.VersionSupport) Map(java.util.Map) PlacementUtils(org.eclipse.winery.model.adaptation.placement.PlacementUtils) URI(java.net.URI) TEntityType(org.eclipse.winery.model.tosca.TEntityType) WineryVersionUtils(org.eclipse.winery.repository.backend.WineryVersionUtils) Context(javax.ws.rs.core.Context) SolutionInputData(org.eclipse.winery.model.adaptation.problemsolving.SolutionInputData) TopologyAndErrorList(org.eclipse.winery.model.adaptation.enhance.TopologyAndErrorList) Allocation(org.eclipse.winery.repository.targetallocation.Allocation) TNodeType(org.eclipse.winery.model.tosca.TNodeType) Collectors(java.util.stream.Collectors) RepositoryFactory(org.eclipse.winery.repository.backend.RepositoryFactory) CompositionData(org.eclipse.winery.repository.rest.resources._support.dataadapter.composeadapter.CompositionData) NewVersionListElement(org.eclipse.winery.repository.rest.resources.apiData.NewVersionListElement) Objects(java.util.Objects) List(java.util.List) PropertyDefinitionKV(org.eclipse.winery.model.tosca.extensions.kvproperties.PropertyDefinitionKV) Response(javax.ws.rs.core.Response) IRepository(org.eclipse.winery.repository.backend.IRepository) Optional(java.util.Optional) RestUtils(org.eclipse.winery.repository.rest.RestUtils) UriInfo(javax.ws.rs.core.UriInfo) QName(javax.xml.namespace.QName) AllocationRequest(org.eclipse.winery.repository.targetallocation.util.AllocationRequest) AbstractComponentInstanceResourceContainingATopology(org.eclipse.winery.repository.rest.resources._support.AbstractComponentInstanceResourceContainingATopology) GET(javax.ws.rs.GET) Splitting(org.eclipse.winery.repository.splitting.Splitting) ServiceTemplateId(org.eclipse.winery.model.ids.definitions.ServiceTemplateId) TEntityTemplate(org.eclipse.winery.model.tosca.TEntityTemplate) HashMap(java.util.HashMap) EnhancementUtils(org.eclipse.winery.model.adaptation.enhance.EnhancementUtils) TTopologyTemplate(org.eclipse.winery.model.tosca.TTopologyTemplate) ArrayList(java.util.ArrayList) LinkedHashMap(java.util.LinkedHashMap) BackendUtils(org.eclipse.winery.repository.backend.BackendUtils) TNodeTemplate(org.eclipse.winery.model.tosca.TNodeTemplate) POST(javax.ws.rs.POST) Logger(org.slf4j.Logger) Environments(org.eclipse.winery.common.configuration.Environments) HasTags(org.eclipse.winery.model.tosca.HasTags) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) IOException(java.io.IOException) DeploymentTechnologyDescriptor(org.eclipse.winery.model.tosca.DeploymentTechnologyDescriptor) TRelationshipTemplate(org.eclipse.winery.model.tosca.TRelationshipTemplate) PropertyDiffList(org.eclipse.winery.repository.rest.resources.apiData.PropertyDiffList) PUT(javax.ws.rs.PUT) ModelUtilities(org.eclipse.winery.model.tosca.utils.ModelUtilities) Collections(java.util.Collections) SolutionFactory(org.eclipse.winery.model.adaptation.problemsolving.SolutionFactory) NodeTypeId(org.eclipse.winery.model.ids.definitions.NodeTypeId) PropertyDefinitionKV(org.eclipse.winery.model.tosca.extensions.kvproperties.PropertyDefinitionKV) TEntityTemplate(org.eclipse.winery.model.tosca.TEntityTemplate) QName(javax.xml.namespace.QName) TEntityType(org.eclipse.winery.model.tosca.TEntityType) ArrayList(java.util.ArrayList) NodeTypeId(org.eclipse.winery.model.ids.definitions.NodeTypeId) PropertyDiffList(org.eclipse.winery.repository.rest.resources.apiData.PropertyDiffList) IRepository(org.eclipse.winery.repository.backend.IRepository) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces)

Example 3 with TEntityTemplate

use of org.eclipse.winery.model.tosca.TEntityTemplate 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)

Example 4 with TEntityTemplate

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

the class ConsistencyChecker method checkPropertiesValidation.

private void checkPropertiesValidation(DefinitionsChildId id) {
    if (!(id instanceof EntityTemplateId)) {
        return;
    }
    TEntityTemplate entityTemplate;
    try {
        // TEntityTemplate is abstract. IRepository does not offer getElement for abstract ids
        // Therefore, we have to use the detour through getDefinitions
        entityTemplate = (TEntityTemplate) configuration.getRepository().getDefinitions(id).getElement();
    } catch (IllegalStateException e) {
        LOGGER.debug("Illegal State Exception during reading of id {}", id.toReadableString(), e);
        printAndAddError(id, "Reading error " + e.getMessage());
        return;
    } catch (ClassCastException e) {
        LOGGER.error("Something wrong in the consistency between Ids and the TOSCA data model. See http://eclipse.github.io/winery/dev/id-system.html for more information on the ID system.");
        printAndAddError(id, "Critical error at analysis: " + e.getMessage());
        return;
    }
    if (Objects.isNull(entityTemplate.getType())) {
        // no printing necessary; type consistency is checked at other places
        return;
    }
    TEntityType entityType;
    try {
        entityType = configuration.getRepository().getTypeForTemplate(entityTemplate);
    } catch (IllegalStateException e) {
        LOGGER.debug("Illegal State Exception during getting type for template {}", entityTemplate.getId(), e);
        printAndAddError(id, "Reading error " + e.getMessage());
        return;
    }
    TEntityTemplate.Properties definedProps = entityTemplate.getProperties();
    if (requiresProperties(entityType) && definedProps == null) {
        printAndAddError(id, "Properties required, but no properties defined");
        return;
    } else if (!requiresProperties(entityType) && definedProps != null) {
        printAndAddError(id, "No properties required by type, but properties were defined on template");
        return;
    } else if (definedProps == null) {
        // no properties required and none defined
        return;
    }
    if (definedProps instanceof TEntityTemplate.XmlProperties) {
        // check defined properties any against the xml schema
        @Nullable final Object any = ((TEntityTemplate.XmlProperties) definedProps).getAny();
        if (any == null) {
            printAndAddError(id, "Properties required, but no XmlProperties were empty (any case)");
            return;
        }
        TEntityType.PropertiesDefinition def = entityType.getProperties();
        if (def == null) {
            printAndAddError(id, "XmlProperties were given, but no XmlPropertiesDefinition was specified");
            return;
        }
        if (def instanceof TEntityType.XmlElementDefinition) {
            final QName element = ((TEntityType.XmlElementDefinition) def).getElement();
            final Map<String, RepositoryFileReference> mapFromLocalNameToXSD = configuration.getRepository().getXsdImportManager().getMapFromLocalNameToXSD(new Namespace(element.getNamespaceURI(), false), false);
            final RepositoryFileReference repositoryFileReference = mapFromLocalNameToXSD.get(element.getLocalPart());
            if (repositoryFileReference == null) {
                printAndAddError(id, "No Xml Schema definition found for " + element);
                return;
            }
            validate(repositoryFileReference, any, id);
        }
    } else if (definedProps instanceof TEntityTemplate.WineryKVProperties) {
        final WinerysPropertiesDefinition winerysPropertiesDefinition = entityType.getWinerysPropertiesDefinition();
        Map<String, String> kvProperties = ((TEntityTemplate.WineryKVProperties) definedProps).getKVProperties();
        if (kvProperties.isEmpty()) {
            printAndAddError(id, "Properties required, but no properties set (kvproperties case)");
            return;
        }
        for (PropertyDefinitionKV propertyDefinitionKV : winerysPropertiesDefinition.getPropertyDefinitions()) {
            String key = propertyDefinitionKV.getKey();
            if (kvProperties.get(key) == null) {
                printAndAddError(id, "Property " + key + " required, but not set.");
            } else {
                // removeNamespaceProperties the key from the map to enable checking below whether a property is defined which not requried by the property definition
                kvProperties.remove(key);
            }
        }
        // If any key is left, this is a key not defined at the schema
        for (Object o : kvProperties.keySet()) {
            printAndAddError(id, "Property " + o + " set, but not defined at schema.");
        }
    } else if (definedProps instanceof TEntityTemplate.YamlProperties) {
        // FIXME todo
        LOGGER.debug("YAML Properties checking is not yet implemented!");
    }
}
Also used : EntityTemplateId(org.eclipse.winery.model.ids.definitions.EntityTemplateId) PropertyDefinitionKV(org.eclipse.winery.model.tosca.extensions.kvproperties.PropertyDefinitionKV) TEntityTemplate(org.eclipse.winery.model.tosca.TEntityTemplate) TEntityType(org.eclipse.winery.model.tosca.TEntityType) QName(javax.xml.namespace.QName) WinerysPropertiesDefinition(org.eclipse.winery.model.tosca.extensions.kvproperties.WinerysPropertiesDefinition) Namespace(org.eclipse.winery.model.ids.Namespace) RepositoryFileReference(org.eclipse.winery.repository.common.RepositoryFileReference) Map(java.util.Map) HashMap(java.util.HashMap) Nullable(org.eclipse.jdt.annotation.Nullable)

Example 5 with TEntityTemplate

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

the class IRepository method getReferencedDefinitionsChildIds.

default Collection<DefinitionsChildId> getReferencedDefinitionsChildIds(ComplianceRuleId id) {
    // We have to use a HashSet to ensure that no duplicate ids are added
    // E.g., there may be multiple relationship templates having the same type
    Collection<DefinitionsChildId> ids = new HashSet<>();
    OTComplianceRule complianceRule = this.getElement(id);
    // TODO extend to required Structure
    if (complianceRule.getIdentifier() != null) {
        for (TEntityTemplate entityTemplate : complianceRule.getIdentifier().getNodeTemplateOrRelationshipTemplate()) {
            QName qname = entityTemplate.getType();
            if (entityTemplate instanceof TNodeTemplate) {
                ids.add(new NodeTypeId(qname));
                TNodeTemplate n = (TNodeTemplate) entityTemplate;
                // crawl through deployment artifacts
                List<TDeploymentArtifact> deploymentArtifacts = n.getDeploymentArtifacts();
                if (deploymentArtifacts != null) {
                    for (TDeploymentArtifact da : deploymentArtifacts) {
                        ids.add(new ArtifactTypeId(da.getArtifactType()));
                        if ((qname = da.getArtifactRef()) != null) {
                            ids.add(new ArtifactTemplateId(qname));
                        }
                    }
                }
                getReferencedRequirementTypeIds(ids, n);
                getCapabilitiesReferences(ids, n);
                // crawl through policies
                List<TPolicy> policies = n.getPolicies();
                if (policies != null) {
                    for (TPolicy pol : policies) {
                        QName type = pol.getPolicyType();
                        PolicyTypeId ctId = new PolicyTypeId(type);
                        ids.add(ctId);
                    }
                }
            } else {
                assert (entityTemplate instanceof TRelationshipTemplate);
                ids.add(new RelationshipTypeId(qname));
            }
        }
    }
    return ids;
}
Also used : RelationshipTypeId(org.eclipse.winery.model.ids.definitions.RelationshipTypeId) DefinitionsChildId(org.eclipse.winery.model.ids.definitions.DefinitionsChildId) TEntityTemplate(org.eclipse.winery.model.tosca.TEntityTemplate) ArtifactTypeId(org.eclipse.winery.model.ids.definitions.ArtifactTypeId) QName(javax.xml.namespace.QName) ArtifactTemplateId(org.eclipse.winery.model.ids.definitions.ArtifactTemplateId) PolicyTypeId(org.eclipse.winery.model.ids.definitions.PolicyTypeId) TRelationshipTemplate(org.eclipse.winery.model.tosca.TRelationshipTemplate) TPolicy(org.eclipse.winery.model.tosca.TPolicy) TDeploymentArtifact(org.eclipse.winery.model.tosca.TDeploymentArtifact) NodeTypeId(org.eclipse.winery.model.ids.definitions.NodeTypeId) TNodeTemplate(org.eclipse.winery.model.tosca.TNodeTemplate) OTComplianceRule(org.eclipse.winery.model.tosca.extensions.OTComplianceRule) HashSet(java.util.HashSet)

Aggregations

TEntityTemplate (org.eclipse.winery.model.tosca.TEntityTemplate)39 TNodeTemplate (org.eclipse.winery.model.tosca.TNodeTemplate)18 TTopologyTemplate (org.eclipse.winery.model.tosca.TTopologyTemplate)13 QName (javax.xml.namespace.QName)12 ArrayList (java.util.ArrayList)9 TRelationshipTemplate (org.eclipse.winery.model.tosca.TRelationshipTemplate)8 HashSet (java.util.HashSet)7 Map (java.util.Map)7 Consumes (javax.ws.rs.Consumes)7 TDeploymentArtifact (org.eclipse.winery.model.tosca.TDeploymentArtifact)7 TPolicy (org.eclipse.winery.model.tosca.TPolicy)7 List (java.util.List)6 PUT (javax.ws.rs.PUT)6 Produces (javax.ws.rs.Produces)6 OTPatternRefinementModel (org.eclipse.winery.model.tosca.extensions.OTPatternRefinementModel)6 TEntityType (org.eclipse.winery.model.tosca.TEntityType)5 HashMap (java.util.HashMap)4 LinkedHashMap (java.util.LinkedHashMap)4 TCapability (org.eclipse.winery.model.tosca.TCapability)4 Test (org.junit.jupiter.api.Test)4