use of org.eclipse.winery.common.ids.XmlId in project winery by eclipse.
the class FilebasedRepository 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) {
FilebasedRepository.LOGGER.debug("Internal error at invocation of id constructor", e);
// abort everything, return invalid result
return res;
}
res.add(id);
}
} catch (IOException e) {
FilebasedRepository.LOGGER.debug("Cannot close ds", e);
}
return res;
}
use of org.eclipse.winery.common.ids.XmlId in project winery by eclipse.
the class FilebasedRepository method getAllDefinitionsChildIds.
@Override
public <T extends DefinitionsChildId> SortedSet<T> getAllDefinitionsChildIds(Class<T> idClass) {
SortedSet<T> res = new TreeSet<>();
String rootPathFragment = Util.getRootPathFragment(idClass);
Path dir = this.repositoryRoot.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) {
XmlId xmlId = new XmlId(idP.getFileName().toString(), true);
Constructor<T> constructor;
try {
constructor = idClass.getConstructor(Namespace.class, XmlId.class);
} catch (Exception e) {
FilebasedRepository.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) {
FilebasedRepository.LOGGER.debug("Internal error at invocation of id constructor", e);
// abort everything, return invalid result
return res;
}
res.add(id);
}
}
}
} catch (IOException e) {
FilebasedRepository.LOGGER.debug("Cannot close ds", e);
}
return res;
}
use of org.eclipse.winery.common.ids.XmlId in project winery by eclipse.
the class CsarImporter method adjustServiceTemplate.
/**
* In case plans are provided, the plans are imported into Winery's storage
*
* @param rootPath the root path of the extracted csar
* @param tmf the TOSCAMetaFile object used to determine the mime type of the plan
* @param wid Winery's internal id of the service template
* @param st the the service template to be imported {@inheritDoc}
*/
private void adjustServiceTemplate(Path rootPath, TOSCAMetaFile tmf, ServiceTemplateId wid, TServiceTemplate st, final List<String> errors) {
TPlans plans = st.getPlans();
if (plans != null) {
for (TPlan plan : plans.getPlan()) {
PlanModelReference refContainer = plan.getPlanModelReference();
if (refContainer != null) {
String ref = refContainer.getReference();
if (ref != null) {
// URLs are stored encoded -> undo the encoding
ref = Util.URLdecode(ref);
URI refURI;
try {
refURI = new URI(ref);
} catch (URISyntaxException e) {
errors.add(String.format("Invalid URI %1$s", ref));
continue;
}
if (refURI.isAbsolute()) {
// We have to do nothing
continue;
}
Path path = rootPath.resolve(ref);
if (!Files.exists(path)) {
// possibly, the reference is relative to the Definitions subfolder
// COS01 does not make any explicit statement how to resolve the reference here
path = rootPath.resolve("Definitions").resolve(ref);
if (!Files.exists(path)) {
errors.add(String.format("Plan reference %1$s not found", ref));
// we quickly remove the reference to reflect the not-found in the data
refContainer.setReference(null);
continue;
}
}
PlansId plansId = new PlansId(wid);
PlanId pid = new PlanId(plansId, new XmlId(plan.getId(), false));
if (Files.isDirectory(path)) {
errors.add(String.format("Reference %1$s is a directory and Winery currently does not support importing directories", ref));
continue;
}
RepositoryFileReference fref = new RepositoryFileReference(pid, path.getFileName().toString());
importFile(path, fref, tmf, rootPath, errors);
// file is imported
// Adjust the reference
refContainer.setReference("../" + Util.getUrlPath(fref));
}
}
}
}
}
use of org.eclipse.winery.common.ids.XmlId in project winery by eclipse.
the class GenericArtifactsResource method generateArtifact.
// @formatter:off
/**
* @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
GenericArtifactsResource.LOGGER.debug("Invalid content", e);
return Response.status(Status.BAD_REQUEST).entity(e.getMessage()).build();
}
}
// determine artifactTemplate and artifactType
ArtifactTypeId artifactTypeId;
ArtifactTemplateId artifactTemplateId = null;
ArtifactTemplateResource artifactTemplateResource = 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) {
ImplementationArtifact a = new ImplementationArtifact();
// Winery internal id is the name of the artifact:
// store the name
a.setName(apiData.artifactName);
a.setInterfaceName(apiData.interfaceName);
a.setOperationName(apiData.operationName);
assert (artifactTypeId != null);
a.setArtifactType(artifactTypeId.getQName());
if (artifactTemplateId != null) {
a.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...
a.getAny().add(doc.getDocumentElement());
}
this.list.add((ArtifactT) a);
resultingArtifact = (ArtifactT) a;
} else {
// for comments see other branch
TDeploymentArtifact a = new TDeploymentArtifact();
a.setName(apiData.artifactName);
assert (artifactTypeId != null);
a.setArtifactType(artifactTypeId.getQName());
if (artifactTemplateId != null) {
a.setArtifactRef(artifactTemplateId.getQName());
}
if (doc != null) {
a.getAny().add(doc.getDocumentElement());
}
this.list.add((ArtifactT) a);
resultingArtifact = (ArtifactT) a;
}
Response persistResponse = RestUtils.persist(super.res);
if (StringUtils.isEmpty(apiData.autoGenerateIA)) {
return Response.created(RestUtils.createURI(Util.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);
}
}
Aggregations