Search in sources :

Example 61 with ServiceTemplateId

use of org.eclipse.winery.model.ids.definitions.ServiceTemplateId in project winery by eclipse.

the class ToscaGraphIsomorphismTest method testServiceTemplateAndComplianceRuleAssociation.

@Test
public void testServiceTemplateAndComplianceRuleAssociation() throws IOException {
    HashMap<DefinitionsChildId, TExtensibleElements> allEntities = new HashMap<>();
    String dirABC = "/ABC";
    String dirBCD = "/BCD";
    ServiceTemplateId stId = new ServiceTemplateId(new QName(TEST_TARGET_NAMESPACE + dirABC + dirBCD, "test1"));
    TServiceTemplate tServiceTemplate = createTServiceTemplate("ServiceTemplateTestId", TEST_TARGET_NAMESPACE + dirABC + dirBCD);
    allEntities.put(stId, tServiceTemplate);
    ComplianceRuleId crId1 = new ComplianceRuleId(new QName(TEST_TARGET_NAMESPACE, "test1"));
    ComplianceRuleId crId2 = new ComplianceRuleId(new QName(TEST_TARGET_NAMESPACE + dirABC, "test2"));
    ComplianceRuleId crId3 = new ComplianceRuleId(new QName(TEST_TARGET_NAMESPACE + dirABC, "test3"));
    ComplianceRuleId crId4 = new ComplianceRuleId(new QName(TEST_TARGET_NAMESPACE + dirBCD, "test4"));
    OTComplianceRule ruleOne = createTComplianceRule(crId1);
    allEntities.put(crId1, ruleOne);
    OTComplianceRule ruleTwo = createTComplianceRule(crId2);
    allEntities.put(crId2, ruleTwo);
    OTComplianceRule ruleThree = createTComplianceRule(crId3);
    allEntities.put(crId3, ruleThree);
    OTComplianceRule ruleFour = createTComplianceRule(crId4);
    allEntities.put(crId4, ruleFour);
    persist(allEntities);
    ServiceTemplateComplianceRuleRuleChecker checker = new ServiceTemplateComplianceRuleRuleChecker(tServiceTemplate);
    List<ComplianceRuleId> ruleIds = checker.getRuleIds(tServiceTemplate);
    assertTrue(ruleIds.stream().anyMatch(id -> id.equals(crId1)));
    assertTrue(ruleIds.stream().anyMatch(id -> id.equals(crId2)));
    assertTrue(ruleIds.stream().anyMatch(id -> id.equals(crId3)));
    assertFalse(ruleIds.stream().anyMatch(id -> id.equals(crId4)));
}
Also used : Arrays(java.util.Arrays) ToscaModelHelper.createTNodeType(org.eclipse.winery.compliance.ToscaModelHelper.createTNodeType) ToscaModelHelper.createTOSCANode(org.eclipse.winery.compliance.ToscaModelHelper.createTOSCANode) Marshaller(javax.xml.bind.Marshaller) GraphMapping(org.jgrapht.GraphMapping) ServiceTemplateCheckingResult(org.eclipse.winery.compliance.checking.ServiceTemplateCheckingResult) ServiceTemplateId(org.eclipse.winery.model.ids.definitions.ServiceTemplateId) ComplianceRuleId(org.eclipse.winery.model.ids.extensions.ComplianceRuleId) HashMap(java.util.HashMap) ToscaModelHelper.createTTopologyTemplate(org.eclipse.winery.compliance.ToscaModelHelper.createTTopologyTemplate) ToscaModelHelper.setDerivedFrom(org.eclipse.winery.compliance.ToscaModelHelper.setDerivedFrom) ToscaEdge(org.eclipse.winery.topologygraph.model.ToscaEdge) TServiceTemplate(org.eclipse.winery.model.tosca.TServiceTemplate) OTComplianceRule(org.eclipse.winery.model.tosca.extensions.OTComplianceRule) ToscaComplianceRuleMatcher(org.eclipse.winery.compliance.checking.ToscaComplianceRuleMatcher) Assertions.assertFalse(org.junit.jupiter.api.Assertions.assertFalse) ToscaIsomorphismMatcher(org.eclipse.winery.topologygraph.matching.ToscaIsomorphismMatcher) BackendUtils(org.eclipse.winery.repository.backend.BackendUtils) Map(java.util.Map) DefinitionsChildId(org.eclipse.winery.model.ids.definitions.DefinitionsChildId) ToscaModelHelper.createTOSCANodeOnlyTypes(org.eclipse.winery.compliance.ToscaModelHelper.createTOSCANodeOnlyTypes) TNodeTemplate(org.eclipse.winery.model.tosca.TNodeTemplate) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) ToscaModelHelper.createTServiceTemplate(org.eclipse.winery.compliance.ToscaModelHelper.createTServiceTemplate) ToscaModelHelper.addEdge(org.eclipse.winery.compliance.ToscaModelHelper.addEdge) JAXBContext(javax.xml.bind.JAXBContext) ServiceTemplateComplianceRuleRuleChecker(org.eclipse.winery.compliance.checking.ServiceTemplateComplianceRuleRuleChecker) ToscaModelHelper.createTNodeTemplate(org.eclipse.winery.compliance.ToscaModelHelper.createTNodeTemplate) Iterator(java.util.Iterator) StringWriter(java.io.StringWriter) IOException(java.io.IOException) TNodeType(org.eclipse.winery.model.tosca.TNodeType) JAXBException(javax.xml.bind.JAXBException) ToscaModelHelper.createTOSCANodeOnlyProperties(org.eclipse.winery.compliance.ToscaModelHelper.createTOSCANodeOnlyProperties) Test(org.junit.jupiter.api.Test) ToscaModelHelper.createTComplianceRule(org.eclipse.winery.compliance.ToscaModelHelper.createTComplianceRule) List(java.util.List) TExtensibleElements(org.eclipse.winery.model.tosca.TExtensibleElements) TestWithGitBackedRepository(org.eclipse.winery.repository.TestWithGitBackedRepository) Lists.newArrayList(com.google.common.collect.Lists.newArrayList) ToscaNode(org.eclipse.winery.topologygraph.model.ToscaNode) ToscaModelHelper.createNodeTypeId(org.eclipse.winery.compliance.ToscaModelHelper.createNodeTypeId) Assertions.assertTrue(org.junit.jupiter.api.Assertions.assertTrue) ToscaGraph(org.eclipse.winery.topologygraph.model.ToscaGraph) QName(javax.xml.namespace.QName) TEST_TARGET_NAMESPACE(org.eclipse.winery.compliance.ToscaModelHelper.TEST_TARGET_NAMESPACE) NodeTypeId(org.eclipse.winery.model.ids.definitions.NodeTypeId) ServiceTemplateComplianceRuleRuleChecker(org.eclipse.winery.compliance.checking.ServiceTemplateComplianceRuleRuleChecker) DefinitionsChildId(org.eclipse.winery.model.ids.definitions.DefinitionsChildId) HashMap(java.util.HashMap) QName(javax.xml.namespace.QName) TExtensibleElements(org.eclipse.winery.model.tosca.TExtensibleElements) ServiceTemplateId(org.eclipse.winery.model.ids.definitions.ServiceTemplateId) ComplianceRuleId(org.eclipse.winery.model.ids.extensions.ComplianceRuleId) OTComplianceRule(org.eclipse.winery.model.tosca.extensions.OTComplianceRule) TServiceTemplate(org.eclipse.winery.model.tosca.TServiceTemplate) ToscaModelHelper.createTServiceTemplate(org.eclipse.winery.compliance.ToscaModelHelper.createTServiceTemplate) Test(org.junit.jupiter.api.Test)

Example 62 with ServiceTemplateId

use of org.eclipse.winery.model.ids.definitions.ServiceTemplateId in project winery by eclipse.

the class IRepository method getReferenceCount.

default int getReferenceCount(ArtifactTemplateId id) {
    // We do not use a database, therefore, we have to go through all possibilities pointing to the artifact template
    // DAs and IAs point to an artifact template
    // DAs are contained in Node Type Implementations and Node Templates
    // IAs are contained in Node Type Implementations and Relationship Type Implementations
    int count = 0;
    Collection<TDeploymentArtifact> allDAs = new HashSet<>();
    Collection<TImplementationArtifact> allIAs = new HashSet<>();
    // handle Node Type Implementation, which contains DAs and IAs
    SortedSet<NodeTypeImplementationId> nodeTypeImplementations = this.getAllDefinitionsChildIds(NodeTypeImplementationId.class);
    for (NodeTypeImplementationId ntiId : nodeTypeImplementations) {
        final TNodeTypeImplementation nodeTypeImplementation = this.getElement(ntiId);
        List<TDeploymentArtifact> deploymentArtifacts = nodeTypeImplementation.getDeploymentArtifacts();
        if (deploymentArtifacts != null) {
            allDAs.addAll(deploymentArtifacts);
        }
        List<TImplementationArtifact> implementationArtifacts = nodeTypeImplementation.getImplementationArtifacts();
        if (implementationArtifacts != null) {
            allIAs.addAll(implementationArtifacts);
        }
    }
    // check all RelationshipTypeImplementations for IAs
    SortedSet<RelationshipTypeImplementationId> relationshipTypeImplementations = this.getAllDefinitionsChildIds(RelationshipTypeImplementationId.class);
    for (RelationshipTypeImplementationId rtiId : relationshipTypeImplementations) {
        List<TImplementationArtifact> implementationArtifacts = this.getElement(rtiId).getImplementationArtifacts();
        if (implementationArtifacts != null) {
            allIAs.addAll(implementationArtifacts);
        }
    }
    // check all node templates for DAs
    SortedSet<ServiceTemplateId> serviceTemplates = this.getAllDefinitionsChildIds(ServiceTemplateId.class);
    for (ServiceTemplateId sid : serviceTemplates) {
        TTopologyTemplate topologyTemplate = this.getElement(sid).getTopologyTemplate();
        if (topologyTemplate != null) {
            List<TEntityTemplate> nodeTemplateOrRelationshipTemplate = topologyTemplate.getNodeTemplateOrRelationshipTemplate();
            for (TEntityTemplate template : nodeTemplateOrRelationshipTemplate) {
                if (template instanceof TNodeTemplate) {
                    TNodeTemplate nodeTemplate = (TNodeTemplate) template;
                    List<TDeploymentArtifact> deploymentArtifacts = nodeTemplate.getDeploymentArtifacts();
                    if (deploymentArtifacts != null) {
                        allDAs.addAll(deploymentArtifacts);
                    }
                }
            }
        }
    }
    // now we have all DAs and IAs
    QName ourQName = id.getQName();
    // check DAs for artifact templates
    for (TDeploymentArtifact da : allDAs) {
        QName artifactRef = da.getArtifactRef();
        if (ourQName.equals(artifactRef)) {
            count++;
        }
    }
    // check IAs for artifact templates
    for (TImplementationArtifact ia : allIAs) {
        QName artifactRef = ia.getArtifactRef();
        if (ourQName.equals(artifactRef)) {
            count++;
        }
    }
    return count;
}
Also used : NodeTypeImplementationId(org.eclipse.winery.model.ids.definitions.NodeTypeImplementationId) TImplementationArtifact(org.eclipse.winery.model.tosca.TImplementationArtifact) TEntityTemplate(org.eclipse.winery.model.tosca.TEntityTemplate) QName(javax.xml.namespace.QName) TNodeTypeImplementation(org.eclipse.winery.model.tosca.TNodeTypeImplementation) RelationshipTypeImplementationId(org.eclipse.winery.model.ids.definitions.RelationshipTypeImplementationId) ServiceTemplateId(org.eclipse.winery.model.ids.definitions.ServiceTemplateId) TTopologyTemplate(org.eclipse.winery.model.tosca.TTopologyTemplate) TDeploymentArtifact(org.eclipse.winery.model.tosca.TDeploymentArtifact) TNodeTemplate(org.eclipse.winery.model.tosca.TNodeTemplate) HashSet(java.util.HashSet)

Example 63 with ServiceTemplateId

use of org.eclipse.winery.model.ids.definitions.ServiceTemplateId in project winery by eclipse.

the class ServiceTemplateResource method createPlaceholderSubstituteVersion.

@Path("placeholdersubstitution")
@POST()
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response createPlaceholderSubstituteVersion() throws IOException, SplittingException {
    TTopologyTemplate originTopologyTemplate = this.getServiceTemplate().getTopologyTemplate();
    if (originTopologyTemplate == null) {
        return Response.notModified().build();
    }
    List<TTag> tagsOfServiceTemplate = this.getServiceTemplate().getTags();
    List<OTParticipant> participants = originTopologyTemplate.getParticipants();
    String participantId = "";
    List<TTag> newTagList = new ArrayList<>();
    for (TTag tagOfServiceTemplate : tagsOfServiceTemplate) {
        if (tagOfServiceTemplate.getName().equals("participant")) {
            participantId = tagOfServiceTemplate.getValue();
            newTagList.add(tagOfServiceTemplate);
        } else if (!tagOfServiceTemplate.getName().equals("choreography")) {
            newTagList.add(tagOfServiceTemplate);
        }
    }
    final String finalParticipantId = participantId;
    List<String> nodeTemplatesWithNewHost = new ArrayList<>();
    for (TNodeTemplate tNodeTemplate : originTopologyTemplate.getNodeTemplates()) {
        // Multiple participants can be annotated on one node template
        Optional<String> nodeOwners = ModelUtilities.getParticipant(tNodeTemplate);
        if (nodeOwners.isPresent() && nodeOwners.get().contains(finalParticipantId)) {
            for (TRelationshipTemplate tRelationshipTemplate : ModelUtilities.getIncomingRelationshipTemplates(originTopologyTemplate, tNodeTemplate)) {
                nodeTemplatesWithNewHost.add(ModelUtilities.getSourceNodeTemplateOfRelationshipTemplate(originTopologyTemplate, tRelationshipTemplate).getId());
            }
        }
    }
    ServiceTemplateId id = (ServiceTemplateId) this.getId();
    WineryVersion version = VersionUtils.getVersion(id.getXmlId().getDecoded());
    WineryVersion newVersion = new WineryVersion("_substituted_" + version.toString(), 1, 1);
    ServiceTemplateId newId = new ServiceTemplateId(id.getNamespace().getDecoded(), VersionUtils.getNameWithoutVersion(id.getXmlId().getDecoded()) + WineryVersion.WINERY_NAME_FROM_VERSION_SEPARATOR + newVersion.toString(), false);
    IRepository repo = RepositoryFactory.getRepository();
    if (repo.exists(newId)) {
        repo.forceDelete(newId);
    }
    ResourceResult response = RestUtils.duplicate(id, newId);
    TServiceTemplate newServiceTemplate = repo.getElement(newId);
    newServiceTemplate.setTopologyTemplate(BackendUtils.clone(originTopologyTemplate));
    newServiceTemplate.getTopologyTemplate().setParticipants(participants);
    Splitting splitting = new Splitting();
    Map<String, List<TTopologyTemplate>> resultList = splitting.getHostingInjectionOptions(BackendUtils.clone(newServiceTemplate.getTopologyTemplate()));
    for (Map.Entry<String, List<TTopologyTemplate>> entry : resultList.entrySet()) {
        Optional<String> nodeOwners = ModelUtilities.getParticipant(newServiceTemplate.getTopologyTemplate().getNodeTemplate(entry.getKey()));
        if (nodeOwners.isPresent() && nodeOwners.get().contains(finalParticipantId)) {
            if (nodeTemplatesWithNewHost.contains(entry.getKey()) && !resultList.get(entry.getKey()).isEmpty()) {
                Map<String, TTopologyTemplate> choiceTopologyTemplate = new LinkedHashMap<>();
                choiceTopologyTemplate.put(entry.getKey(), entry.getValue().get(0));
                splitting.injectNodeTemplates(newServiceTemplate.getTopologyTemplate(), choiceTopologyTemplate, InjectRemoval.REMOVE_REPLACED);
                for (TNodeTemplate injectNodeTemplate : choiceTopologyTemplate.get(entry.getKey()).getNodeTemplates()) {
                    injectNodeTemplate.getOtherAttributes().put(QNAME_PARTICIPANT, finalParticipantId);
                }
            }
        }
    }
    String choreoValue = splitting.calculateChoreographyTag(newServiceTemplate.getTopologyTemplate().getNodeTemplates(), participantId);
    TTag choreoTag = new TTag();
    choreoTag.setName("choreography");
    choreoTag.setValue(choreoValue);
    newTagList.add(choreoTag);
    newServiceTemplate.setTags(newTagList);
    repo.setElement(newId, newServiceTemplate);
    if (response.getStatus() == Status.CREATED) {
        response.setUri(null);
        response.setMessage(new QNameApiData(newId));
    }
    return response.getResponse();
}
Also used : TTag(org.eclipse.winery.model.tosca.TTag) QNameApiData(org.eclipse.winery.repository.rest.resources.apiData.QNameApiData) ArrayList(java.util.ArrayList) ServiceTemplateId(org.eclipse.winery.model.ids.definitions.ServiceTemplateId) OTParticipant(org.eclipse.winery.model.tosca.extensions.OTParticipant) LinkedHashMap(java.util.LinkedHashMap) ResourceResult(org.eclipse.winery.repository.rest.resources._support.ResourceResult) Splitting(org.eclipse.winery.repository.splitting.Splitting) TTopologyTemplate(org.eclipse.winery.model.tosca.TTopologyTemplate) TRelationshipTemplate(org.eclipse.winery.model.tosca.TRelationshipTemplate) List(java.util.List) ArrayList(java.util.ArrayList) IRepository(org.eclipse.winery.repository.backend.IRepository) TNodeTemplate(org.eclipse.winery.model.tosca.TNodeTemplate) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) WineryVersion(org.eclipse.winery.common.version.WineryVersion) TServiceTemplate(org.eclipse.winery.model.tosca.TServiceTemplate) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Produces(javax.ws.rs.Produces)

Example 64 with ServiceTemplateId

use of org.eclipse.winery.model.ids.definitions.ServiceTemplateId in project winery by eclipse.

the class ServiceTemplateResource method setTopology.

@Override
public void setTopology(TTopologyTemplate topologyTemplate, String type) {
    // if we are in yaml mode, replacing the topology can result in yaml artifacts having to be deleted.
    if (Environments.getInstance().getRepositoryConfig().getProvider() == RepositoryConfigurationObject.RepositoryProvider.YAML) {
        try {
            YamlArtifactsSynchronizer synchronizer = new YamlArtifactsSynchronizer.Builder(RepositoryFactory.getRepository()).setOriginalTemplate(this.getServiceTemplate().getTopologyTemplate()).setNewTemplate(topologyTemplate).setServiceTemplateId((ServiceTemplateId) this.getId()).build();
            synchronizer.synchronizeNodeTemplates();
            synchronizer.synchronizeRelationshipTemplates();
        } catch (IOException e) {
            LOGGER.error("Failed to delete yaml artifact files from disk. Reason {}", e.getMessage());
        }
        if (topologyTemplate.getNodeTemplates().stream().filter(nt -> nt.getRequirements() != null).anyMatch(nt -> nt.getRequirements().stream().anyMatch(req -> req.getRelationship() != null))) {
            // filter unused requirements
            // (1) get a list of requirement template ids
            // (2) filter requirement entry on node template if there is relations assigned
            Set<String> usedRelationshipTemplateIds = topologyTemplate.getRelationshipTemplates().stream().map(HasId::getId).collect(Collectors.toSet());
            topologyTemplate.getNodeTemplates().stream().filter(node -> node.getRequirements() != null).forEach(node -> node.getRequirements().removeIf(r -> !usedRelationshipTemplateIds.contains(r.getRelationship())));
        }
    }
    this.getServiceTemplate().setTopologyTemplate(topologyTemplate);
    this.cullElementReferences();
}
Also used : EdmmUtils(org.eclipse.winery.edmm.EdmmUtils) Produces(javax.ws.rs.Produces) TBoundaryDefinitions(org.eclipse.winery.model.tosca.TBoundaryDefinitions) PlansResource(org.eclipse.winery.repository.rest.resources.servicetemplates.plans.PlansResource) Date(java.util.Date) TopologyTemplateResource(org.eclipse.winery.repository.rest.resources.servicetemplates.topologytemplates.TopologyTemplateResource) Path(javax.ws.rs.Path) LoggerFactory(org.slf4j.LoggerFactory) SelfServicePortalResource(org.eclipse.winery.repository.rest.resources.servicetemplates.selfserviceportal.SelfServicePortalResource) TServiceTemplate(org.eclipse.winery.model.tosca.TServiceTemplate) WineryVersion(org.eclipse.winery.common.version.WineryVersion) ApiOperation(io.swagger.annotations.ApiOperation) MediaType(javax.ws.rs.core.MediaType) Consumes(javax.ws.rs.Consumes) Namespaces(org.eclipse.winery.model.tosca.constants.Namespaces) SplittingException(org.eclipse.winery.repository.splitting.SplittingException) VersionSupport(org.eclipse.winery.model.version.VersionSupport) Map(java.util.Map) TRequirement(org.eclipse.winery.model.tosca.TRequirement) URI(java.net.URI) DELETE(javax.ws.rs.DELETE) ThreatAssessment(org.eclipse.winery.model.threatmodeling.ThreatAssessment) ServiceTemplateComplianceRuleRuleChecker(org.eclipse.winery.compliance.checking.ServiceTemplateComplianceRuleRuleChecker) QNameApiData(org.eclipse.winery.repository.rest.resources.apiData.QNameApiData) Context(javax.ws.rs.core.Context) Collection(java.util.Collection) Set(java.util.Set) TNodeType(org.eclipse.winery.model.tosca.TNodeType) WinerysPropertiesDefinition(org.eclipse.winery.model.tosca.extensions.kvproperties.WinerysPropertiesDefinition) Collectors(java.util.stream.Collectors) JAXBException(javax.xml.bind.JAXBException) HasId(org.eclipse.winery.model.tosca.HasId) TInterface(org.eclipse.winery.model.tosca.TInterface) RepositoryFactory(org.eclipse.winery.repository.backend.RepositoryFactory) BoundaryDefinitionsResource(org.eclipse.winery.repository.rest.resources.servicetemplates.boundarydefinitions.BoundaryDefinitionsResource) List(java.util.List) PropertyDefinitionKV(org.eclipse.winery.model.tosca.extensions.kvproperties.PropertyDefinitionKV) TExtensibleElements(org.eclipse.winery.model.tosca.TExtensibleElements) Response(javax.ws.rs.core.Response) TPlan(org.eclipse.winery.model.tosca.TPlan) VersionUtils(org.eclipse.winery.common.version.VersionUtils) TCapability(org.eclipse.winery.model.tosca.TCapability) 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) ToscaBaseTypes(org.eclipse.winery.model.tosca.constants.ToscaBaseTypes) AbstractComponentInstanceResourceContainingATopology(org.eclipse.winery.repository.rest.resources._support.AbstractComponentInstanceResourceContainingATopology) GET(javax.ws.rs.GET) YamlArtifactsSynchronizer(org.eclipse.winery.repository.backend.YamlArtifactsSynchronizer) Splitting(org.eclipse.winery.repository.splitting.Splitting) ServiceTemplateCheckingResult(org.eclipse.winery.compliance.checking.ServiceTemplateCheckingResult) ServiceTemplateId(org.eclipse.winery.model.ids.definitions.ServiceTemplateId) SimpleDateFormat(java.text.SimpleDateFormat) ApiResponses(io.swagger.annotations.ApiResponses) TTopologyTemplate(org.eclipse.winery.model.tosca.TTopologyTemplate) ArrayList(java.util.ArrayList) LinkedHashMap(java.util.LinkedHashMap) TParameter(org.eclipse.winery.model.tosca.TParameter) InjectorReplaceOptions(org.eclipse.winery.repository.rest.resources._support.dataadapter.injectionadapter.InjectorReplaceOptions) ThreatModeling(org.eclipse.winery.model.threatmodeling.ThreatModeling) BackendUtils(org.eclipse.winery.repository.backend.BackendUtils) TCapabilityRef(org.eclipse.winery.model.tosca.TCapabilityRef) TNodeTemplate(org.eclipse.winery.model.tosca.TNodeTemplate) Status(javax.ws.rs.core.Response.Status) Substitution(org.eclipse.winery.model.adaptation.substitution.Substitution) ResourceResult(org.eclipse.winery.repository.rest.resources._support.ResourceResult) POST(javax.ws.rs.POST) TRequirementRef(org.eclipse.winery.model.tosca.TRequirementRef) Logger(org.slf4j.Logger) Iterator(java.util.Iterator) OTParticipant(org.eclipse.winery.model.tosca.extensions.OTParticipant) Environments(org.eclipse.winery.common.configuration.Environments) IOException(java.io.IOException) InjectRemoval(org.eclipse.winery.repository.splitting.InjectRemoval) TPropertyMapping(org.eclipse.winery.model.tosca.TPropertyMapping) TTag(org.eclipse.winery.model.tosca.TTag) InjectorReplaceData(org.eclipse.winery.repository.rest.resources._support.dataadapter.injectionadapter.InjectorReplaceData) EdmmResource(org.eclipse.winery.repository.rest.resources.edmm.EdmmResource) NamespaceManager(org.eclipse.winery.repository.backend.NamespaceManager) DASpecification(org.eclipse.winery.repository.driverspecificationandinjection.DASpecification) ApiResponse(io.swagger.annotations.ApiResponse) TRelationshipTemplate(org.eclipse.winery.model.tosca.TRelationshipTemplate) RepositoryConfigurationObject(org.eclipse.winery.common.configuration.RepositoryConfigurationObject) TOperation(org.eclipse.winery.model.tosca.TOperation) ModelUtilities(org.eclipse.winery.model.tosca.utils.ModelUtilities) DriverInjection(org.eclipse.winery.repository.driverspecificationandinjection.DriverInjection) NodeTypeId(org.eclipse.winery.model.ids.definitions.NodeTypeId) IHasName(org.eclipse.winery.repository.rest.resources._support.IHasName) YamlArtifactsSynchronizer(org.eclipse.winery.repository.backend.YamlArtifactsSynchronizer) IOException(java.io.IOException) ServiceTemplateId(org.eclipse.winery.model.ids.definitions.ServiceTemplateId)

Example 65 with ServiceTemplateId

use of org.eclipse.winery.model.ids.definitions.ServiceTemplateId in project winery by eclipse.

the class ServiceTemplatesResource method createFromArtifact.

@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response createFromArtifact(@FormDataParam("file") InputStream uploadedInputStream, @FormDataParam("file") FormDataContentDisposition fileDetail, @FormDataParam("file") FormDataBodyPart body, @FormDataParam("artifactType") QName artifactType, @FormDataParam("nodeTypes") List<FormDataBodyPart> nodeTypesList, @FormDataParam("infrastructureNodeType") QName infrastructureNodeType, @FormDataParam("tags") List<FormDataBodyPart> sentTagsList, @Context UriInfo uriInfo) throws IllegalArgumentException, JAXBException, IOException {
    Set<String> sentTags = new HashSet<>();
    if (sentTagsList != null) {
        for (FormDataBodyPart tag : sentTagsList) {
            sentTags.add(tag.getValue());
        }
    }
    Set<String> tags = RestUtils.clean(sentTags);
    Set<QName> nodeTypes = new HashSet<>();
    for (FormDataBodyPart nodetype : nodeTypesList) {
        nodeTypes.add(QName.valueOf(nodetype.getValue()));
    }
    nodeTypes = RestUtils.cleanQNameSet(nodeTypes);
    Collection<ServiceTemplateId> xaasPackages = this.getXaaSPackageTemplates(artifactType);
    Collection<ServiceTemplateId> toRemove = new ArrayList<>();
    // check whether the serviceTemplate contains all the given nodeTypes
    for (ServiceTemplateId serviceTemplate : xaasPackages) {
        if (!RestUtils.containsNodeTypes(new ServiceTemplateResource(serviceTemplate).getServiceTemplate(), nodeTypes) | !RestUtils.containsTags(new ServiceTemplateResource(serviceTemplate).getServiceTemplate(), tags)) {
            toRemove.add(serviceTemplate);
            continue;
        }
        if (infrastructureNodeType != null && !infrastructureNodeType.getLocalPart().equals("undefined")) {
            if (RestUtils.getTagValue(new ServiceTemplateResource(serviceTemplate).getServiceTemplate(), "xaasPackageInfrastructure") == null) {
                toRemove.add(serviceTemplate);
            } else {
                String value = RestUtils.getTagValue(new ServiceTemplateResource(serviceTemplate).getServiceTemplate(), "xaasPackageInfrastructure");
                if (value != null) {
                    String localName = value.split("}")[1];
                    String namespace = value.split("}")[0].substring(1);
                    if (!infrastructureNodeType.equals(new QName(namespace, localName))) {
                        toRemove.add(serviceTemplate);
                    }
                }
            }
        }
    }
    xaasPackages.removeAll(toRemove);
    if (xaasPackages.size() <= 0) {
        return Response.serverError().entity("No suitable ServiceTemplate found for given artifact and configuration").build();
    }
    // take the first found serviceTemplate
    ServiceTemplateId serviceTemplate = xaasPackages.iterator().next();
    // create new name for the cloned sTemplate
    String newTemplateName = fileDetail.getFileName() + "ServiceTemplate";
    // create artifactTemplate for the uploaded artifact
    ArtifactTemplateId artifactTemplateId = RestUtils.createArtifactTemplate(uploadedInputStream, fileDetail, body, artifactType, uriInfo);
    // clone serviceTemplate
    ServiceTemplateId serviceTemplateId = RestUtils.cloneServiceTemplate(serviceTemplate, newTemplateName, fileDetail.getFileName());
    if (RestUtils.hasDA(serviceTemplateId, RestUtils.getTagValue(new ServiceTemplateResource(serviceTemplate).getServiceTemplate(), "xaasPackageNode"), RestUtils.getTagValue(new ServiceTemplateResource(serviceTemplate).getServiceTemplate(), "xaasPackageDeploymentArtifact"))) {
        // inject artifact as DA into cloned ServiceTemplate
        BackendUtils.injectArtifactTemplateIntoDeploymentArtifact(serviceTemplateId, RestUtils.getTagValue(new ServiceTemplateResource(serviceTemplate).getServiceTemplate(), "xaasPackageNode"), RestUtils.getTagValue(new ServiceTemplateResource(serviceTemplate).getServiceTemplate(), "xaasPackageDeploymentArtifact"), artifactTemplateId, requestRepository);
    } else {
        return Response.serverError().entity("Tagged DeploymentArtifact could not be found on given specified NodeTemplate").build();
    }
    URI absUri = RestUtils.getAbsoluteURI(serviceTemplateId);
    // http://localhost:8080/winery/servicetemplates/winery/servicetemplates/http%253A%252F%252Fopentosca.org%252Fservicetemplates/hs_err_pid13228.logServiceTemplate/
    // http://localhost:8080/winery/servicetemplates/winery/servicetemplates/http%253A%252F%252Fopentosca.org%252Fservicetemplates/java0.logServiceTemplate/
    String absUriString = absUri.toString().replace("/winery/servicetemplates", "");
    absUri = URI.create(absUriString);
    return Response.created(absUri).build();
}
Also used : FormDataBodyPart(org.glassfish.jersey.media.multipart.FormDataBodyPart) QName(javax.xml.namespace.QName) ArrayList(java.util.ArrayList) ServiceTemplateId(org.eclipse.winery.model.ids.definitions.ServiceTemplateId) URI(java.net.URI) ArtifactTemplateId(org.eclipse.winery.model.ids.definitions.ArtifactTemplateId) HashSet(java.util.HashSet) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes)

Aggregations

ServiceTemplateId (org.eclipse.winery.model.ids.definitions.ServiceTemplateId)126 Test (org.junit.jupiter.api.Test)73 TServiceTemplate (org.eclipse.winery.model.tosca.TServiceTemplate)44 ArrayList (java.util.ArrayList)41 TTopologyTemplate (org.eclipse.winery.model.tosca.TTopologyTemplate)40 TNodeTemplate (org.eclipse.winery.model.tosca.TNodeTemplate)35 QName (javax.xml.namespace.QName)25 IOException (java.io.IOException)24 IRepository (org.eclipse.winery.repository.backend.IRepository)19 List (java.util.List)17 POST (javax.ws.rs.POST)17 Path (javax.ws.rs.Path)16 Produces (javax.ws.rs.Produces)16 HashMap (java.util.HashMap)15 TopologyWrapper (org.eclipse.winery.repository.targetallocation.util.TopologyWrapper)15 Map (java.util.Map)14 TRelationshipTemplate (org.eclipse.winery.model.tosca.TRelationshipTemplate)14 URI (java.net.URI)13 NodeTypeId (org.eclipse.winery.model.ids.definitions.NodeTypeId)13 TNodeType (org.eclipse.winery.model.tosca.TNodeType)13