Search in sources :

Example 6 with PropertyDefinitionKV

use of org.eclipse.winery.model.tosca.extensions.kvproperties.PropertyDefinitionKV in project winery by eclipse.

the class ModelUtilities method mergePropertiesDefinitions.

/**
 * Merge properties definitions.
 * Only winery properties definitions are considered.
 * The first element in the list is the lowest in the inheritance hierarchy.
 */
public static <T extends TEntityType> List<PropertyDefinitionKV> mergePropertiesDefinitions(List<T> entityTypes) {
    List<PropertyDefinitionKV> propertyDefinitions = new ArrayList<>();
    for (int i = 0; i < entityTypes.size(); i++) {
        TEntityType entityType = entityTypes.get(i);
        WinerysPropertiesDefinition winerysPropertiesDefinition = entityType.getWinerysPropertiesDefinition();
        // Continue if current entity type does not have any properties definitions
        if (winerysPropertiesDefinition == null) {
            continue;
        }
        // Continue if current entity type does not have any properties definitions
        List<PropertyDefinitionKV> winerysPropertiesDefinitions = winerysPropertiesDefinition.getPropertyDefinitions();
        if (winerysPropertiesDefinitions == null) {
            continue;
        }
        // Add property definition to list if not already added by a previous entity type
        for (PropertyDefinitionKV entityTypePropertyDefinition : winerysPropertiesDefinitions) {
            boolean exists = false;
            for (PropertyDefinitionKV propertyDefinition : propertyDefinitions) {
                if (Objects.equals(propertyDefinition.getKey(), entityTypePropertyDefinition.getKey())) {
                    if (i == 1) {
                        propertyDefinition.setDerivedFromStatus("OVERRIDE");
                    }
                    exists = true;
                    break;
                }
            }
            if (!exists) {
                entityTypePropertyDefinition.setDerivedFromType(entityType.getQName());
                if (i == 0) {
                    entityTypePropertyDefinition.setDerivedFromStatus("SELF");
                } else {
                    entityTypePropertyDefinition.setDerivedFromStatus("INHERITED");
                }
                propertyDefinitions.add(entityTypePropertyDefinition);
            }
        }
    }
    return propertyDefinitions;
}
Also used : PropertyDefinitionKV(org.eclipse.winery.model.tosca.extensions.kvproperties.PropertyDefinitionKV) TEntityType(org.eclipse.winery.model.tosca.TEntityType) ArrayList(java.util.ArrayList) WinerysPropertiesDefinition(org.eclipse.winery.model.tosca.extensions.kvproperties.WinerysPropertiesDefinition)

Example 7 with PropertyDefinitionKV

use of org.eclipse.winery.model.tosca.extensions.kvproperties.PropertyDefinitionKV in project winery by eclipse.

the class ModelUtilities method getWinerysPropertiesDefinitionXsdAsDocument.

/**
 * Generates a XSD when Winery's K/V properties are used. This method is put here instead of
 * WinerysPropertiesDefinitionResource to avoid generating the subresource
 * <p>
 * public because of the usage by TOSCAExportUtil
 *
 * @return empty Document, if Winery's Properties Definition is not fully filled (e.g., no wrapping element defined)
 */
public static Document getWinerysPropertiesDefinitionXsdAsDocument(WinerysPropertiesDefinition wpd) {
    /*
         * This is a quick hack: an XML schema container is created for each
         * element. Smarter solution: create a hash from namespace to XML schema
         * element and re-use that for each new element
         * Drawback of "smarter" solution: not a single XSD file anymore
         */
    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder;
    try {
        docBuilder = docFactory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        ModelUtilities.LOGGER.debug(e.getMessage(), e);
        throw new IllegalStateException("Could not instantiate document builder", e);
    }
    Document doc = docBuilder.newDocument();
    if (!ModelUtilities.allRequiredFieldsNonNull(wpd)) {
        // wpd not fully filled -> valid XSD cannot be provided
        // fallback: add comment and return "empty" document
        Comment comment = doc.createComment("Required fields are missing in Winery's key/value properties definition.");
        doc.appendChild(comment);
        return doc;
    }
    // create XSD schema container
    Element schemaElement = doc.createElementNS(XMLConstants.W3C_XML_SCHEMA_NS_URI, "schema");
    doc.appendChild(schemaElement);
    schemaElement.setAttribute("elementFormDefault", "qualified");
    schemaElement.setAttribute("attributeFormDefault", "unqualified");
    schemaElement.setAttribute("targetNamespace", wpd.getNamespace());
    // create XSD element itself
    Element el = doc.createElementNS(XMLConstants.W3C_XML_SCHEMA_NS_URI, "element");
    schemaElement.appendChild(el);
    el.setAttribute("name", wpd.getElementName());
    Element el2 = doc.createElementNS(XMLConstants.W3C_XML_SCHEMA_NS_URI, "complexType");
    el.appendChild(el2);
    el = el2;
    el2 = doc.createElementNS(XMLConstants.W3C_XML_SCHEMA_NS_URI, "sequence");
    el.appendChild(el2);
    el = el2;
    // currently, "xsd" is a hardcoded prefix in the type definition
    el.setAttribute("xmlns:xsd", XMLConstants.W3C_XML_SCHEMA_NS_URI);
    for (PropertyDefinitionKV prop : wpd.getPropertyDefinitions()) {
        el2 = doc.createElementNS(XMLConstants.W3C_XML_SCHEMA_NS_URI, "element");
        el.appendChild(el2);
        el2.setAttribute("name", prop.getKey());
        // prop.getType has the prefix included
        el2.setAttribute("type", prop.getType());
    }
    return doc;
}
Also used : Comment(org.w3c.dom.Comment) DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) PropertyDefinitionKV(org.eclipse.winery.model.tosca.extensions.kvproperties.PropertyDefinitionKV) DocumentBuilder(javax.xml.parsers.DocumentBuilder) Element(org.w3c.dom.Element) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) Document(org.w3c.dom.Document)

Example 8 with PropertyDefinitionKV

use of org.eclipse.winery.model.tosca.extensions.kvproperties.PropertyDefinitionKV in project winery by eclipse.

the class ServiceTemplateResource method generateInputParameters.

private void generateInputParameters(List<PropertyDefinitionKV> propertyDefinitionKVList, LinkedHashMap<String, String> placeholderNodeTemplateProperties, TNodeType sourceNodeType, TParameter inputParameter) {
    PropertyDefinitionKV inputParamKV = new PropertyDefinitionKV(inputParameter.getName(), inputParameter.getType());
    if (sourceNodeType.getWinerysPropertiesDefinition() != null && !sourceNodeType.getWinerysPropertiesDefinition().getPropertyDefinitions().contains(inputParamKV) && !propertyDefinitionKVList.contains(inputParamKV)) {
        propertyDefinitionKVList.add(inputParamKV);
        placeholderNodeTemplateProperties.put(inputParameter.getName(), "get_input: " + inputParameter.getName());
    }
}
Also used : PropertyDefinitionKV(org.eclipse.winery.model.tosca.extensions.kvproperties.PropertyDefinitionKV)

Example 9 with PropertyDefinitionKV

use of org.eclipse.winery.model.tosca.extensions.kvproperties.PropertyDefinitionKV in project winery by eclipse.

the class ServiceTemplateResource method generatePlaceholdersWithCapability.

@POST
@Path("placeholder/generator")
@Consumes({ MediaType.APPLICATION_XML, MediaType.TEXT_XML, MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_XML, MediaType.TEXT_XML, MediaType.APPLICATION_JSON })
public Response generatePlaceholdersWithCapability() {
    Splitting splitting = new Splitting();
    TTopologyTemplate topologyTemplate = this.getServiceTemplate().getTopologyTemplate();
    if (topologyTemplate == null) {
        return Response.notModified().build();
    }
    try {
        // get all open requirements and the respective node templates with open requirements
        Map<TRequirement, TNodeTemplate> requirementsAndItsNodeTemplates = splitting.getOpenRequirementsAndItsNodeTemplate(topologyTemplate);
        IRepository repo = RepositoryFactory.getRepository();
        // iterate over all open requirements
        for (Map.Entry<TRequirement, TNodeTemplate> entry : requirementsAndItsNodeTemplates.entrySet()) {
            List<PropertyDefinitionKV> propertyDefinitionKVList = new ArrayList<>();
            LinkedHashMap<String, String> placeholderNodeTemplateProperties = new LinkedHashMap<>();
            // current node template with open requirements
            TNodeTemplate nodeTemplateWithOpenReq = entry.getValue();
            // get type of node template with open requirements
            NodeTypeId id = new NodeTypeId(nodeTemplateWithOpenReq.getType());
            TNodeType sourceNodeType = repo.getElement(id);
            List<TInterface> sourceNodeTypeInterfaces = sourceNodeType.getInterfaces();
            if (sourceNodeTypeInterfaces != null) {
                for (TInterface tInterface : sourceNodeTypeInterfaces) {
                    // TODO: make this more safe
                    for (TOperation tOperation : tInterface.getOperations()) {
                        List<TParameter> inputParameters = tOperation.getInputParameters();
                        if (inputParameters != null) {
                            for (TParameter inputParameter : inputParameters) {
                                generateInputParameters(propertyDefinitionKVList, placeholderNodeTemplateProperties, sourceNodeType, inputParameter);
                            }
                        }
                    }
                }
            }
            List<TRelationshipTemplate> incomingRelationshipTemplates = ModelUtilities.getIncomingRelationshipTemplates(topologyTemplate, nodeTemplateWithOpenReq);
            List<TParameter> inputParameters = splitting.getInputParamListofIncomingRelationshipTemplates(topologyTemplate, incomingRelationshipTemplates);
            for (TParameter inputParameter : inputParameters) {
                String prefixTARGET = "TARGET_";
                String prefixSOURCE = "SOURCE_";
                String inputParamName = inputParameter.getName();
                if (inputParamName.contains(prefixTARGET)) {
                    inputParamName = inputParamName.replaceAll(prefixTARGET, "");
                }
                if (inputParamName.contains(prefixSOURCE)) {
                    inputParamName = inputParamName.replaceAll(prefixSOURCE, "");
                }
                inputParameter.setName(inputParamName);
                generateInputParameters(propertyDefinitionKVList, placeholderNodeTemplateProperties, sourceNodeType, inputParameter);
            }
            // get required capability type of open requirement
            QName capabilityType = splitting.getRequiredCapabilityTypeQNameOfRequirement(entry.getKey());
            // create new placeholder node type
            TNodeType placeholderNodeType = splitting.createPlaceholderNodeType(nodeTemplateWithOpenReq.getName());
            QName placeholderQName = new QName(placeholderNodeType.getTargetNamespace(), placeholderNodeType.getName());
            WinerysPropertiesDefinition winerysPropertiesDefinition = sourceNodeType.getWinerysPropertiesDefinition();
            // add properties definition
            placeholderNodeType.setProperties(null);
            if (winerysPropertiesDefinition != null) {
                winerysPropertiesDefinition.setPropertyDefinitions(propertyDefinitionKVList);
                placeholderNodeType.setProperties(winerysPropertiesDefinition);
                String namespace = placeholderNodeType.getWinerysPropertiesDefinition().getNamespace();
                NamespaceManager namespaceManager = RepositoryFactory.getRepository().getNamespaceManager();
                if (!namespaceManager.hasPermanentProperties(namespace)) {
                    namespaceManager.addPermanentNamespace(namespace);
                }
            }
            NodeTypeId placeholderId = new NodeTypeId(placeholderQName);
            // check if placeholder node type exists
            if (repo.exists(placeholderId)) {
                // delete and create new
                RestUtils.delete(placeholderId);
            }
            repo.setElement(placeholderId, placeholderNodeType);
            // create placeholder node template
            TNodeTemplate placeholderNodeTemplate = splitting.createPlaceholderNodeTemplate(topologyTemplate, nodeTemplateWithOpenReq.getName(), placeholderQName);
            // create capability of placeholder node template
            TCapability capa = splitting.createPlaceholderCapability(topologyTemplate, capabilityType);
            ModelUtilities.setPropertiesKV(placeholderNodeTemplate, placeholderNodeTemplateProperties);
            if (placeholderNodeTemplate.getCapabilities() == null) {
                placeholderNodeTemplate.setCapabilities(new ArrayList<>());
            }
            placeholderNodeTemplate.getCapabilities().add(capa);
            for (Map.Entry<QName, String> targetLocation : nodeTemplateWithOpenReq.getOtherAttributes().entrySet()) {
                placeholderNodeTemplate.getOtherAttributes().put(targetLocation.getKey(), targetLocation.getValue());
            }
            // add placeholder to node template and connect with source node template with open requirements
            topologyTemplate.addNodeTemplate(placeholderNodeTemplate);
            ModelUtilities.createRelationshipTemplateAndAddToTopology(nodeTemplateWithOpenReq, placeholderNodeTemplate, ToscaBaseTypes.hostedOnRelationshipType, topologyTemplate);
        }
        LOGGER.debug("PERSISTING");
        RestUtils.persist(this);
        LOGGER.debug("PERSISTED");
        String responseId = this.getServiceTemplate().getId();
        return Response.ok().entity(responseId).build();
    } catch (Exception e) {
        LOGGER.error("Could not fetch requirements and capabilities", e);
        return Response.status(Status.BAD_REQUEST).entity(e.getMessage()).build();
    }
}
Also used : NamespaceManager(org.eclipse.winery.repository.backend.NamespaceManager) PropertyDefinitionKV(org.eclipse.winery.model.tosca.extensions.kvproperties.PropertyDefinitionKV) TInterface(org.eclipse.winery.model.tosca.TInterface) ArrayList(java.util.ArrayList) WinerysPropertiesDefinition(org.eclipse.winery.model.tosca.extensions.kvproperties.WinerysPropertiesDefinition) LinkedHashMap(java.util.LinkedHashMap) TRequirement(org.eclipse.winery.model.tosca.TRequirement) TOperation(org.eclipse.winery.model.tosca.TOperation) TTopologyTemplate(org.eclipse.winery.model.tosca.TTopologyTemplate) TRelationshipTemplate(org.eclipse.winery.model.tosca.TRelationshipTemplate) TNodeTemplate(org.eclipse.winery.model.tosca.TNodeTemplate) QName(javax.xml.namespace.QName) TCapability(org.eclipse.winery.model.tosca.TCapability) SplittingException(org.eclipse.winery.repository.splitting.SplittingException) JAXBException(javax.xml.bind.JAXBException) IOException(java.io.IOException) TNodeType(org.eclipse.winery.model.tosca.TNodeType) Splitting(org.eclipse.winery.repository.splitting.Splitting) NodeTypeId(org.eclipse.winery.model.ids.definitions.NodeTypeId) IRepository(org.eclipse.winery.repository.backend.IRepository) TParameter(org.eclipse.winery.model.tosca.TParameter) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces)

Example 10 with PropertyDefinitionKV

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

Aggregations

PropertyDefinitionKV (org.eclipse.winery.model.tosca.extensions.kvproperties.PropertyDefinitionKV)21 WinerysPropertiesDefinition (org.eclipse.winery.model.tosca.extensions.kvproperties.WinerysPropertiesDefinition)16 TEntityType (org.eclipse.winery.model.tosca.TEntityType)11 ArrayList (java.util.ArrayList)9 LinkedHashMap (java.util.LinkedHashMap)8 QName (javax.xml.namespace.QName)8 TNodeType (org.eclipse.winery.model.tosca.TNodeType)8 NodeTypeId (org.eclipse.winery.model.ids.definitions.NodeTypeId)7 IOException (java.io.IOException)6 TEntityTemplate (org.eclipse.winery.model.tosca.TEntityTemplate)6 TNodeTemplate (org.eclipse.winery.model.tosca.TNodeTemplate)6 TRelationshipTemplate (org.eclipse.winery.model.tosca.TRelationshipTemplate)6 IRepository (org.eclipse.winery.repository.backend.IRepository)6 Map (java.util.Map)5 Path (javax.ws.rs.Path)5 Produces (javax.ws.rs.Produces)5 HashMap (java.util.HashMap)4 Consumes (javax.ws.rs.Consumes)4 POST (javax.ws.rs.POST)4 List (java.util.List)3