use of org.eclipse.winery.model.tosca.extensions.kvproperties.WinerysPropertiesDefinition in project winery by eclipse.
the class EnhancementUtils method createFeatureNodeType.
/**
* This method merges the Basic-NodeType of the given nodeTemplate with the selected Feature-NodeTypes and generates
* respective implementations.
*
* @param nodeTemplate The NodeTemplate that is updated with the selected features.
* @param featureTypes The list of selected features as generated by {@link #getAvailableFeaturesForTopology(TTopologyTemplate,
* List}.
* @return The mapping of the generated merged NodeType and the QName of the NodeType it replaces.
*/
public static TNodeType createFeatureNodeType(TNodeTemplate nodeTemplate, Map<QName, String> featureTypes) {
IRepository repository = RepositoryFactory.getRepository();
Map<QName, TNodeType> nodeTypes = repository.getQNameToElementMapping(NodeTypeId.class);
Map<QName, TNodeTypeImplementation> nodeTypeImplementations = repository.getQNameToElementMapping(NodeTypeImplementationId.class);
StringBuilder featureNames = new StringBuilder();
featureTypes.values().forEach(featureName -> {
if (!featureNames.toString().isEmpty()) {
featureNames.append("-");
}
featureNames.append(featureName.replaceAll("\\s", "_"));
});
// merge type
String namespace = generateNewGeneratedNamespace(nodeTemplate.getType());
TNodeType featureEnrichedNodeType = nodeTypes.get(nodeTemplate.getType());
featureEnrichedNodeType.setTargetNamespace(namespace);
featureEnrichedNodeType.setName(nodeTemplate.getType().getLocalPart() + "-" + nodeTemplate.getId() + "-" + featureNames + WineryVersion.WINERY_VERSION_SEPARATOR + WineryVersion.WINERY_VERSION_PREFIX + "1");
// prepare Properties
if (Objects.isNull(featureEnrichedNodeType.getWinerysPropertiesDefinition())) {
WinerysPropertiesDefinition props = new WinerysPropertiesDefinition();
props.setPropertyDefinitions(new ArrayList<>());
ModelUtilities.replaceWinerysPropertiesDefinition(featureEnrichedNodeType, props);
}
List<PropertyDefinitionKV> baseProperties = featureEnrichedNodeType.getWinerysPropertiesDefinition().getPropertyDefinitions();
// prepare Interfaces
if (Objects.isNull(featureEnrichedNodeType.getInterfaces())) {
featureEnrichedNodeType.setInterfaces(new ArrayList<>());
}
List<TInterface> baseInterfaces = featureEnrichedNodeType.getInterfaces();
// merge impl accordingly
TNodeTypeImplementation generatedImplementation = new TNodeTypeImplementation.Builder(featureEnrichedNodeType.getName() + "_Impl" + WineryVersion.WINERY_VERSION_SEPARATOR + WineryVersion.WINERY_VERSION_PREFIX + "1", featureEnrichedNodeType.getQName()).build();
// ensure that the lists are initialized
generatedImplementation.setImplementationArtifacts(new ArrayList<>());
generatedImplementation.setDeploymentArtifacts(new ArrayList<>());
Collection<NodeTypeImplementationId> baseTypeImplementations = repository.getAllElementsReferencingGivenType(NodeTypeImplementationId.class, nodeTemplate.getType());
if (baseTypeImplementations.size() > 0) {
for (NodeTypeImplementationId id : baseTypeImplementations) {
if (Objects.isNull(generatedImplementation.getTargetNamespace())) {
generatedImplementation.setTargetNamespace(generateNewGeneratedNamespace(id.getQName()));
}
addAllDAsAndIAsToImplementation(generatedImplementation, nodeTypeImplementations.get(id.getQName()));
}
} else {
// This should never be the case. However, we implement it as a valid fallback.
generatedImplementation.setTargetNamespace(namespace.replace("nodetypes", "nodetypeimplementations"));
}
featureTypes.keySet().forEach(featureTypeQName -> {
TNodeType nodeType = nodeTypes.get(featureTypeQName);
// merge Properties
if (Objects.nonNull(nodeType.getWinerysPropertiesDefinition())) {
List<PropertyDefinitionKV> kvList = nodeType.getWinerysPropertiesDefinition().getPropertyDefinitions();
if (Objects.nonNull(kvList) && !kvList.isEmpty()) {
for (PropertyDefinitionKV kv : kvList) {
boolean listContainsProperty = baseProperties.stream().anyMatch(property -> property.getKey().equals(kv.getKey()));
if (!listContainsProperty) {
baseProperties.add(kv);
}
}
}
}
// merge Interfaces
if (Objects.nonNull(nodeType.getInterfaces()) && !nodeType.getInterfaces().isEmpty()) {
baseInterfaces.addAll(nodeType.getInterfaces());
}
// merge implementations
repository.getAllElementsReferencingGivenType(NodeTypeImplementationId.class, featureTypeQName).forEach(id -> addAllDAsAndIAsToImplementation(generatedImplementation, nodeTypeImplementations.get(id.getQName())));
});
// remove them from the type to ensure a compliant XML.
if (Objects.nonNull(featureEnrichedNodeType.getWinerysPropertiesDefinition()) && Objects.nonNull(featureEnrichedNodeType.getWinerysPropertiesDefinition().getPropertyDefinitions()) && featureEnrichedNodeType.getWinerysPropertiesDefinition().getPropertyDefinitions().isEmpty()) {
ModelUtilities.removeWinerysPropertiesDefinition(featureEnrichedNodeType);
}
try {
repository.setElement(new NodeTypeId(featureEnrichedNodeType.getQName()), featureEnrichedNodeType);
repository.setElement(new NodeTypeImplementationId(generatedImplementation.getQName()), generatedImplementation);
} catch (IOException e) {
logger.error("Error while saving generated definitions.", e);
}
return featureEnrichedNodeType;
}
use of org.eclipse.winery.model.tosca.extensions.kvproperties.WinerysPropertiesDefinition 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!");
}
}
use of org.eclipse.winery.model.tosca.extensions.kvproperties.WinerysPropertiesDefinition in project winery by eclipse.
the class PropertiesDefinitionSerializer method serialize.
@Override
public void serialize(TEntityType.PropertiesDefinition propertiesDefinition, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
jsonGenerator.writeStartObject();
if (propertiesDefinition instanceof WinerysPropertiesDefinition) {
WinerysPropertiesDefinition wpd = (WinerysPropertiesDefinition) propertiesDefinition;
jsonGenerator.writeStringField("namespace", wpd.getNamespace());
jsonGenerator.writeStringField("elementName", wpd.getElementName());
jsonGenerator.writeArrayFieldStart("propertyDefinitionKVList");
JsonSerializer<Object> defSerializer = serializerProvider.findValueSerializer(PropertyDefinitionKV.class);
if (wpd.getPropertyDefinitions() != null) {
for (PropertyDefinitionKV propDef : wpd.getPropertyDefinitions()) {
defSerializer.serialize(propDef, jsonGenerator, serializerProvider);
}
}
jsonGenerator.writeEndArray();
if (wpd.getIsDerivedFromXSD() != null && wpd.getIsDerivedFromXSD()) {
jsonGenerator.writeBooleanField("isDerivedFromXSD", wpd.getIsDerivedFromXSD());
}
} else if (propertiesDefinition instanceof TEntityType.XmlElementDefinition) {
jsonGenerator.writeStringField("element", ((TEntityType.XmlElementDefinition) propertiesDefinition).getElement().toString());
} else if (propertiesDefinition instanceof TEntityType.XmlTypeDefinition) {
jsonGenerator.writeStringField("type", ((TEntityType.XmlTypeDefinition) propertiesDefinition).getType().toString());
} else if (propertiesDefinition instanceof TEntityType.YamlPropertiesDefinition) {
jsonGenerator.writeArrayFieldStart("properties");
JsonSerializer<Object> yamlDefSerializer = serializerProvider.findValueSerializer(TEntityType.YamlPropertyDefinition.class);
for (TEntityType.YamlPropertyDefinition def : ((TEntityType.YamlPropertiesDefinition) propertiesDefinition).getProperties()) {
yamlDefSerializer.serialize(def, jsonGenerator, serializerProvider);
}
jsonGenerator.writeEndArray();
} else {
// this basically throws an exception
serializerProvider.reportBadDefinition(TEntityType.PropertiesDefinition.class, "Unknown subtype of PropertiesDefinition passed for serialization.");
}
jsonGenerator.writeEndObject();
}
use of org.eclipse.winery.model.tosca.extensions.kvproperties.WinerysPropertiesDefinition in project winery by eclipse.
the class ThreatModelingUtils method setupThreatModelingTypes.
/**
* create all Policy Types and Node Types required for threat modeling
*
* @throws Exception if setup was already done
*/
public void setupThreatModelingTypes() throws Exception {
if (checkPrerequisites()) {
throw new Exception("Threat modeling already set up.");
}
TPolicyType threat = new TPolicyType();
threat.setId(ThreatModelingConstants.THREAT_POLICY_NAME);
threat.setName(ThreatModelingConstants.THREAT_POLICY_NAME);
threat.setAbstract(false);
threat.setFinal(false);
threat.setTargetNamespace(ThreatModelingConstants.THREATMODELING_NAMESPACE);
threat.setProperties(null);
WinerysPropertiesDefinition threatProps = new WinerysPropertiesDefinition();
threatProps.setElementName("properties");
threatProps.setNamespace(ThreatModelingConstants.THREATMODELING_NAMESPACE.concat("/propertiesdefinition/winery"));
List<PropertyDefinitionKV> threatPropList = new ArrayList<>(Arrays.asList(new PropertyDefinitionKV(ThreatModelingProperties.description.toString(), "xsd:string"), new PropertyDefinitionKV(ThreatModelingProperties.strideClassification.toString(), "xsd:string"), new PropertyDefinitionKV(ThreatModelingProperties.severity.toString(), "xsd:string")));
threatProps.setPropertyDefinitions(threatPropList);
ModelUtilities.replaceWinerysPropertiesDefinition(threat, threatProps);
PolicyTypeId threatID = BackendUtils.getDefinitionsChildId(PolicyTypeId.class, ThreatModelingConstants.THREATMODELING_NAMESPACE, ThreatModelingConstants.THREAT_POLICY_NAME, false);
TDefinitions threatDefinitions = BackendUtils.createWrapperDefinitions(threatID, repository);
threatDefinitions.setElement(threat);
TPolicyType mitigation = new TPolicyType();
mitigation.setId(ThreatModelingConstants.MITIGATION_POLICY_NAME);
mitigation.setName(ThreatModelingConstants.MITIGATION_POLICY_NAME);
mitigation.setAbstract(false);
mitigation.setFinal(false);
mitigation.setTargetNamespace(ThreatModelingConstants.THREATMODELING_NAMESPACE);
mitigation.setProperties(null);
WinerysPropertiesDefinition mitigationProps = new WinerysPropertiesDefinition();
List<PropertyDefinitionKV> mitigationPropList = new ArrayList<>();
mitigationProps.setElementName("properties");
mitigationProps.setNamespace(ThreatModelingConstants.THREATMODELING_NAMESPACE.concat("/propertiesdefinition/winery"));
mitigationPropList.add(new PropertyDefinitionKV(ThreatModelingProperties.ThreatReference.toString(), "xsd:string"));
mitigationProps.setPropertyDefinitions(mitigationPropList);
ModelUtilities.replaceWinerysPropertiesDefinition(mitigation, mitigationProps);
PolicyTypeId mitigationID = BackendUtils.getDefinitionsChildId(PolicyTypeId.class, ThreatModelingConstants.THREATMODELING_NAMESPACE, ThreatModelingConstants.MITIGATION_POLICY_NAME, false);
TDefinitions mitigationDefinitions = BackendUtils.createWrapperDefinitions(mitigationID, repository);
mitigationDefinitions.setElement(mitigation);
TNodeType svnf = new TNodeType.Builder("S-VNF-w1_wip1").setTargetNamespace(ThreatModelingConstants.SECURITY_NAMESPACE).setAbstract(true).build();
NodeTypeId svnfID = new NodeTypeId(QName.valueOf(ThreatModelingConstants.SVNF_NODE_TYPE));
TDefinitions svnfDefinitions = BackendUtils.createWrapperDefinitions(svnfID, repository);
svnfDefinitions.setElement(svnf);
try {
BackendUtils.persist(repository, threatID, threatDefinitions);
BackendUtils.persist(repository, mitigationID, mitigationDefinitions);
BackendUtils.persist(repository, svnfID, svnfDefinitions);
} catch (IOException i) {
LOGGER.debug("Could not set up threat modeling", i);
}
}
use of org.eclipse.winery.model.tosca.extensions.kvproperties.WinerysPropertiesDefinition in project winery by eclipse.
the class TEntityType method getWinerysPropertiesDefinition.
/**
* This is a special method for Winery. Winery allows to define a property definition by specifying name/type
* values. Instead of parsing the extensible elements returned TDefinitions, this method is a convenience method to
* access this information
*
* @return a WinerysPropertiesDefinition object, which includes a map of name/type-pairs denoting the associated
* property definitions. A default element name and namespace is added if it is not defined in the underlying XML.
* null if no Winery specific KV properties are defined for the given entity type
*/
@XmlTransient
@JsonIgnore
public WinerysPropertiesDefinition getWinerysPropertiesDefinition() {
if (properties == null || !(properties instanceof WinerysPropertiesDefinition)) {
return null;
}
WinerysPropertiesDefinition res = (WinerysPropertiesDefinition) properties;
// we put defaults if element name and namespace have not been set
if (res.getElementName() == null) {
res.setElementName("Properties");
}
if (res.getNamespace() == null) {
// we use the target namespace of the original element
String ns = this.getTargetNamespace();
if (!ns.endsWith("/")) {
ns += "/";
}
ns += NS_SUFFIX_PROPERTIES_DEFINITION_WINERY;
res.setNamespace(ns);
}
return res;
}
Aggregations