use of org.eclipse.winery.model.ids.XmlId in project winery by eclipse.
the class YamlRepository method getDefinitionsChildIds.
/**
* Creates Set of Definitions Child Id Mapps xml definition to compatible yaml definition
*
* @param inputIdClass requested id class
* @param omitDevelopmentVersions omit development versions
* @return set of definitions child id
*/
@Override
public <T extends DefinitionsChildId> SortedSet<T> getDefinitionsChildIds(Class<T> inputIdClass, boolean omitDevelopmentVersions) {
SortedSet<T> res = new TreeSet<>();
List<Class<T>> idClasses = new ArrayList<>();
idClasses.add(inputIdClass);
idClasses = convertDefinitionsChildIdIfNeeded(idClasses);
for (Class<T> idClass : idClasses) {
String rootPathFragment = IdUtil.getRootPathFragment(idClass);
Path dir = this.getRepositoryRoot().resolve(rootPathFragment);
if (!Files.exists(dir)) {
// return empty list if no ids are available
return res;
}
assert (Files.isDirectory(dir));
final OnlyNonHiddenDirectories onhdf = new OnlyNonHiddenDirectories();
// list all directories contained in this directory
try (DirectoryStream<Path> ds = Files.newDirectoryStream(dir, onhdf)) {
for (Path nsP : ds) {
// the current path is the namespace
Namespace ns = new Namespace(nsP.getFileName().toString(), true);
try (DirectoryStream<Path> idDS = Files.newDirectoryStream(nsP, onhdf)) {
for (Path idP : idDS) {
List<XmlId> xmlIds = new ArrayList<>();
if (ArtifactTemplateId.class.isAssignableFrom(inputIdClass)) {
List<String> artifactNames = getAllArtifactNamesFromType(idP, idClass, ns.getDecoded());
for (String artifactName : artifactNames) {
xmlIds.add(new XmlId(artifactName + "@" + IdUtil.getFolderName(idClass), true));
}
} else {
xmlIds.add(new XmlId(idP.getFileName().toString(), true));
}
for (XmlId xmlId : xmlIds) {
if (omitDevelopmentVersions) {
WineryVersion version = VersionUtils.getVersion(xmlId.getDecoded());
if (version.toString().length() > 0 && version.getWorkInProgressVersion() > 0) {
continue;
}
}
Constructor<T> constructor;
try {
constructor = inputIdClass.getConstructor(Namespace.class, XmlId.class);
} catch (Exception e) {
LOGGER.debug("Internal error at determining id constructor", e);
// abort everything, return invalid result
return res;
}
T id;
try {
id = constructor.newInstance(ns, xmlId);
} catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
LOGGER.debug("Internal error at invocation of id constructor", e);
// abort everything, return invalid result
return res;
}
res.add(id);
}
}
}
}
} catch (IOException e) {
LOGGER.debug("Cannot close ds", e);
}
}
return res;
}
use of org.eclipse.winery.model.ids.XmlId in project winery by eclipse.
the class ImportUtilsTest method getLocationForImportTest.
@Test
public void getLocationForImportTest() throws Exception {
this.setRevisionTo("5fdcffa9ccd17743d5498cab0914081fc33606e9");
XSDImportId id = new XSDImportId(new Namespace("http://opentosca.org/nodetypes", false), new XmlId("CloudProviderProperties", false));
Optional<String> importLocation = ImportUtils.getLocation(repository, id);
assertEquals(true, importLocation.isPresent());
}
use of org.eclipse.winery.model.ids.XmlId in project winery by eclipse.
the class GenericArtifactsResource method generateArtifact.
/**
* @return TImplementationArtifact | TDeploymentArtifact (XML) | URL of generated IA zip (in case of autoGenerateIA)
*/
@POST
@Consumes(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Creates a new implementation/deployment artifact. If an implementation artifact with the same name already exists, it is <em>overridden</em>.")
@SuppressWarnings("unchecked")
public Response generateArtifact(GenerateArtifactApiData apiData, @Context UriInfo uriInfo) {
// we assume that the parent ComponentInstance container exists
final IRepository repository = RepositoryFactory.getRepository();
if (StringUtils.isEmpty(apiData.artifactName)) {
return Response.status(Status.BAD_REQUEST).entity("Empty artifactName").build();
}
if (StringUtils.isEmpty(apiData.artifactType)) {
if (StringUtils.isEmpty(apiData.artifactTemplateName) || StringUtils.isEmpty(apiData.artifactTemplateNamespace)) {
if (StringUtils.isEmpty(apiData.artifactTemplate)) {
return Response.status(Status.BAD_REQUEST).entity("No artifact type given and no template given. Cannot guess artifact type").build();
}
}
}
if (!StringUtils.isEmpty(apiData.autoGenerateIA)) {
if (StringUtils.isEmpty(apiData.javaPackage)) {
return Response.status(Status.BAD_REQUEST).entity("no java package name supplied for IA auto generation.").build();
}
if (StringUtils.isEmpty(apiData.interfaceName)) {
return Response.status(Status.BAD_REQUEST).entity("no interface name supplied for IA auto generation.").build();
}
}
// convert second calling form to first calling form
if (!StringUtils.isEmpty(apiData.artifactTemplate)) {
QName qname = QName.valueOf(apiData.artifactTemplate);
apiData.artifactTemplateName = qname.getLocalPart();
apiData.artifactTemplateNamespace = qname.getNamespaceURI();
}
Document doc = null;
// if invalid, abort and do not create anything
if (!StringUtils.isEmpty(apiData.artifactSpecificContent)) {
try {
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
InputSource is = new InputSource();
StringReader sr = new StringReader(apiData.artifactSpecificContent);
is.setCharacterStream(sr);
doc = db.parse(is);
} catch (Exception e) {
// FIXME: currently we allow a single element only. However, the content should be internally wrapped by an (arbitrary) XML element as the content will be nested in the artifact element, too
LOGGER.debug("Invalid content", e);
return Response.status(Status.BAD_REQUEST).entity(e.getMessage()).build();
}
}
// determine artifactTemplate and artifactType
ArtifactTypeId artifactTypeId;
ArtifactTemplateId artifactTemplateId = null;
boolean doAutoCreateArtifactTemplate = !(StringUtils.isEmpty(apiData.autoCreateArtifactTemplate) || apiData.autoCreateArtifactTemplate.equalsIgnoreCase("no") || apiData.autoCreateArtifactTemplate.equalsIgnoreCase("false"));
if (!doAutoCreateArtifactTemplate) {
// no auto creation
if (!StringUtils.isEmpty(apiData.artifactTemplateName) && !StringUtils.isEmpty(apiData.artifactTemplateNamespace)) {
QName artifactTemplateQName = new QName(apiData.artifactTemplateNamespace, apiData.artifactTemplateName);
artifactTemplateId = BackendUtils.getDefinitionsChildId(ArtifactTemplateId.class, artifactTemplateQName);
}
if (StringUtils.isEmpty(apiData.artifactType)) {
// derive the type from the artifact template
if (artifactTemplateId == null) {
return Response.status(Status.NOT_ACCEPTABLE).entity("No artifactTemplate and no artifactType provided. Deriving the artifactType is not possible.").build();
}
@NonNull final QName type = repository.getElement(artifactTemplateId).getType();
artifactTypeId = BackendUtils.getDefinitionsChildId(ArtifactTypeId.class, type);
} else {
// artifactTypeStr is directly given, use that
artifactTypeId = BackendUtils.getDefinitionsChildId(ArtifactTypeId.class, apiData.artifactType);
}
} else {
if (StringUtils.isEmpty(apiData.artifactType)) {
return Response.status(Status.BAD_REQUEST).entity("Artifact template auto creation requested, but no artifact type supplied.").build();
}
artifactTypeId = BackendUtils.getDefinitionsChildId(ArtifactTypeId.class, apiData.artifactType);
// ensure that given type exists
if (!repository.exists(artifactTypeId)) {
LOGGER.debug("Artifact type {} is created", apiData.artifactType);
final TArtifactType element = repository.getElement(artifactTypeId);
try {
repository.setElement(artifactTypeId, element);
} catch (IOException e) {
throw new WebApplicationException(e);
}
}
if (StringUtils.isEmpty(apiData.artifactTemplateName) || StringUtils.isEmpty(apiData.artifactTemplateNamespace)) {
// no explicit name provided
// we use the artifactNameStr as prefix for the
// artifact template name
// we create a new artifact template in the namespace of the parent
// element
Namespace namespace = this.resWithNamespace.getNamespace();
artifactTemplateId = new ArtifactTemplateId(namespace, new XmlId(apiData.artifactName + "artifactTemplate", false));
} else {
QName artifactTemplateQName = new QName(apiData.artifactTemplateNamespace, apiData.artifactTemplateName);
artifactTemplateId = new ArtifactTemplateId(artifactTemplateQName);
}
// even if artifactTemplate does not exist, it is loaded
final TArtifactTemplate artifactTemplate = repository.getElement(artifactTemplateId);
artifactTemplate.setType(artifactTypeId.getQName());
try {
repository.setElement(artifactTemplateId, artifactTemplate);
} catch (IOException e) {
throw new WebApplicationException(e);
}
}
// variable artifactTypeId is set
// variable artifactTemplateId is not null if artifactTemplate has been generated
// we have to generate the DA/IA resource now
// Doing it here instead of doing it at the subclasses is dirty on the
// one hand, but quicker to implement on the other hand
// Create the artifact itself
ArtifactT resultingArtifact;
if (this instanceof ImplementationArtifactsResource) {
TImplementationArtifact.Builder builder = new TImplementationArtifact.Builder(artifactTypeId.getQName()).setName(apiData.artifactName).setInterfaceName(apiData.interfaceName).setOperationName(apiData.operationName);
if (artifactTemplateId != null) {
builder.setArtifactRef(artifactTemplateId.getQName());
}
if (doc != null) {
// the content has been checked for validity at the beginning of the method.
// If this point in the code is reached, the XML has been parsed into doc
// just copy over the dom node. Hopefully, that works...
builder.setAny(Collections.singletonList(doc.getDocumentElement()));
}
resultingArtifact = (ArtifactT) builder.build();
} else {
// for comments see other branch
TDeploymentArtifact.Builder builder = new TDeploymentArtifact.Builder(apiData.artifactName, artifactTypeId.getQName());
if (artifactTemplateId != null) {
builder.setArtifactRef(artifactTemplateId.getQName());
}
if (doc != null) {
builder.setAny(Collections.singletonList(doc.getDocumentElement()));
}
resultingArtifact = (ArtifactT) builder.build();
}
this.list.add(resultingArtifact);
// TODO: Check for error, and in case one found return it
RestUtils.persist(super.res);
if (StringUtils.isEmpty(apiData.autoGenerateIA)) {
// No IA generation
return Response.created(URI.create(EncodingUtil.URLencode(apiData.artifactName))).entity(resultingArtifact).build();
} else {
// after everything was created, we fire up the artifact generation
return this.generateImplementationArtifact(apiData.interfaceName, apiData.javaPackage, uriInfo, artifactTemplateId);
}
}
use of org.eclipse.winery.model.ids.XmlId in project winery by eclipse.
the class AbstractFileBasedRepository method getNestedIds.
@Override
public <T extends ToscaElementId> SortedSet<T> getNestedIds(GenericId ref, Class<T> idClass) {
Path dir = this.id2AbsolutePath(ref);
SortedSet<T> res = new TreeSet<>();
if (!Files.exists(dir)) {
// This test is done here.
return res;
}
assert (Files.isDirectory(dir));
// list all directories contained in this directory
try (DirectoryStream<Path> ds = Files.newDirectoryStream(dir, new OnlyNonHiddenDirectories())) {
for (Path p : ds) {
XmlId xmlId = new XmlId(p.getFileName().toString(), true);
@SuppressWarnings("unchecked") Constructor<T>[] constructors = (Constructor<T>[]) idClass.getConstructors();
assert (constructors.length == 1);
Constructor<T> constructor = constructors[0];
assert (constructor.getParameterTypes().length == 2);
T id;
try {
id = constructor.newInstance(ref, xmlId);
} catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
LOGGER.debug("Internal error at invocation of id constructor", e);
// abort everything, return invalid result
return res;
}
res.add(id);
}
} catch (IOException e) {
LOGGER.debug("Cannot close ds", e);
}
return res;
}
use of org.eclipse.winery.model.ids.XmlId in project winery by eclipse.
the class BackendUtils method synchronizeReferences.
/**
* Synchronizes the known plans with the data in the XML. When there is a stored file, but no known entry in the
* XML, we guess "BPEL" as language and "buildProvenanceSmartContract plan" as type.
*/
public static void synchronizeReferences(ServiceTemplateId id, IRepository repository) throws IOException {
final TServiceTemplate serviceTemplate = repository.getElement(id);
// locally stored plans
List<TPlan> plans = serviceTemplate.getPlans();
// plans stored in the repository
PlansId plansContainerId = new PlansId(id);
SortedSet<PlanId> nestedPlans = repository.getNestedIds(plansContainerId, PlanId.class);
Set<PlanId> plansToAdd = new HashSet<>(nestedPlans);
if (nestedPlans.isEmpty() && plans == null) {
// data on the file system equals the data -> no plans
return;
}
if (plans == null) {
plans = new ArrayList<>();
serviceTemplate.setPlans(plans);
}
for (Iterator<TPlan> iterator = plans.iterator(); iterator.hasNext(); ) {
TPlan plan = iterator.next();
if (plan.getPlanModel() != null) {
// in case, a plan is directly contained in a Model element, we do not need to do anything
continue;
}
TPlan.PlanModelReference planModelReference;
if ((planModelReference = plan.getPlanModelReference()) != null) {
String ref = planModelReference.getReference();
if ((ref == null) || ref.startsWith("../")) {
// special case (due to errors in the importer): empty PlanModelReference field
if (plan.getId() == null || plan.getId().isEmpty()) {
// invalid plan entry: no id.
// we remove the entry
iterator.remove();
continue;
}
PlanId planId = new PlanId(plansContainerId, new XmlId(plan.getId(), false));
if (nestedPlans.contains(planId)) {
// everything alright
// we do NOT need to add the plan on the HDD to the XML
plansToAdd.remove(planId);
} else {
// no local storage for the plan, we remove it from the XML
iterator.remove();
}
}
}
}
// add all plans locally stored, but not contained in the XML, as plan element to the plans of the service template.
for (PlanId planId : plansToAdd) {
SortedSet<RepositoryFileReference> files = repository.getContainedFiles(planId);
if (files.size() != 1) {
throw new IllegalStateException("Currently, only one file per plan is supported.");
}
RepositoryFileReference ref = files.iterator().next();
TPlan plan = new TPlan.Builder(planId.getXmlId().getDecoded(), Constants.TOSCA_PLANTYPE_BUILD_PLAN, Namespaces.URI_BPEL20_EXECUTABLE).setName(planId.getXmlId().getDecoded()).build();
// create a PlanModelReferenceElement pointing to that file
String path = Util.getUrlPath(ref);
// path is relative from the definitions element
path = "../" + path;
TPlan.PlanModelReference pref = new TPlan.PlanModelReference();
pref.setReference(path);
plan.setPlanModelReference(pref);
plans.add(plan);
}
if (serviceTemplate.getPlans() != null && serviceTemplate.getPlans().isEmpty()) {
serviceTemplate.setPlans(null);
}
repository.setElement(id, serviceTemplate);
}
Aggregations