Search in sources :

Example 6 with DirectoryId

use of org.eclipse.winery.repository.datatypes.ids.elements.DirectoryId in project winery by eclipse.

the class CsarExporter method writeCsar.

/**
 * Writes a complete CSAR containing all necessary things reachable from the given service template
 *
 * @param entryId the id of the service template to export
 * @param out     the output stream to write to
 */
public void writeCsar(IRepository repository, DefinitionsChildId entryId, OutputStream out) throws ArchiveException, IOException, JAXBException, RepositoryCorruptException {
    CsarExporter.LOGGER.trace("Starting CSAR export with {}", entryId.toString());
    Map<RepositoryFileReference, String> refMap = new HashMap<>();
    Collection<String> definitionNames = new ArrayList<>();
    try (final ArchiveOutputStream zos = new ArchiveStreamFactory().createArchiveOutputStream("zip", out)) {
        ToscaExportUtil exporter = new ToscaExportUtil();
        Map<String, Object> conf = new HashMap<>();
        ExportedState exportedState = new ExportedState();
        DefinitionsChildId currentId = entryId;
        do {
            String defName = CsarExporter.getDefinitionsPathInsideCSAR(repository, currentId);
            definitionNames.add(defName);
            zos.putArchiveEntry(new ZipArchiveEntry(defName));
            Collection<DefinitionsChildId> referencedIds;
            referencedIds = exporter.exportTOSCA(repository, currentId, zos, refMap, conf);
            zos.closeArchiveEntry();
            exportedState.flagAsExported(currentId);
            exportedState.flagAsExportRequired(referencedIds);
            currentId = exportedState.pop();
        } while (currentId != null);
        // if we export a ServiceTemplate, data for the self-service portal might exist
        if (entryId instanceof ServiceTemplateId) {
            ServiceTemplateId serviceTemplateId = (ServiceTemplateId) entryId;
            this.addSelfServiceMetaData(repository, serviceTemplateId, refMap);
            this.addSelfServiceFiles(repository, serviceTemplateId, refMap, zos);
        }
        // now, refMap contains all files to be added to the CSAR
        // write manifest directly after the definitions to have it more at the beginning of the ZIP rather than having it at the very end
        this.addManifest(repository, entryId, definitionNames, refMap, zos);
        // used for generated XSD schemas
        TransformerFactory tFactory = TransformerFactory.newInstance();
        Transformer transformer;
        try {
            transformer = tFactory.newTransformer();
        } catch (TransformerConfigurationException e1) {
            CsarExporter.LOGGER.debug(e1.getMessage(), e1);
            throw new IllegalStateException("Could not instantiate transformer", e1);
        }
        // write all referenced files
        for (RepositoryFileReference ref : refMap.keySet()) {
            String archivePath = refMap.get(ref);
            CsarExporter.LOGGER.trace("Creating {}", archivePath);
            if (ref instanceof DummyRepositoryFileReferenceForGeneratedXSD) {
                addDummyRepositoryFileReferenceForGeneratedXSD(zos, transformer, (DummyRepositoryFileReferenceForGeneratedXSD) ref, archivePath);
            } else {
                if (ref.getParent() instanceof DirectoryId) {
                    // special handling for artifact template directories "source" and "files"
                    addArtifactTemplateToZipFile(zos, repository, ref, archivePath);
                } else {
                    addFileToZipArchive(zos, repository, ref, archivePath);
                    zos.closeArchiveEntry();
                }
            }
        }
        this.addNamespacePrefixes(zos, repository);
    }
}
Also used : TransformerFactory(javax.xml.transform.TransformerFactory) Transformer(javax.xml.transform.Transformer) TransformerConfigurationException(javax.xml.transform.TransformerConfigurationException) DefinitionsChildId(org.eclipse.winery.common.ids.definitions.DefinitionsChildId) ServiceTemplateId(org.eclipse.winery.common.ids.definitions.ServiceTemplateId) ArchiveStreamFactory(org.apache.commons.compress.archivers.ArchiveStreamFactory) ServiceTemplateSelfServiceFilesDirectoryId(org.eclipse.winery.repository.datatypes.ids.elements.ServiceTemplateSelfServiceFilesDirectoryId) DirectoryId(org.eclipse.winery.repository.datatypes.ids.elements.DirectoryId) RepositoryFileReference(org.eclipse.winery.common.RepositoryFileReference) ZipArchiveEntry(org.apache.commons.compress.archivers.zip.ZipArchiveEntry) ArchiveOutputStream(org.apache.commons.compress.archivers.ArchiveOutputStream)

Example 7 with DirectoryId

use of org.eclipse.winery.repository.datatypes.ids.elements.DirectoryId in project winery by eclipse.

the class ArtifactTemplateResource method copySourceToFilesResource.

@POST
@Consumes(MediaType.APPLICATION_JSON)
public Response copySourceToFilesResource(@ApiParam(value = "if data contains a non-empty array than only the files" + " whose names are included are copied ", required = true) ArtifactResourcesApiData data) {
    List<String> artifactList = data.getArtifactNames();
    DirectoryId sourceDir = new ArtifactTemplateSourceDirectoryId((ArtifactTemplateId) this.id);
    FilesResource filesResource = getFilesResource();
    for (RepositoryFileReference ref : RepositoryFactory.getRepository().getContainedFiles(sourceDir)) {
        if (artifactList == null || artifactList.contains(ref.getFileName())) {
            try (InputStream inputStream = RepositoryFactory.getRepository().newInputStream(ref)) {
                String fileName = ref.getFileName();
                String subDirectory = ref.getSubDirectory().map(s -> s.toString()).orElse("");
                filesResource.putFile(fileName, subDirectory, inputStream);
            } catch (IOException e) {
                LOGGER.debug("The artifact source " + ref.getFileName() + " could not be copied to the files directory.", e);
                return Response.status(Status.INTERNAL_SERVER_ERROR).build();
            }
        }
    }
    return Response.status(Status.CREATED).build();
}
Also used : MimeTypes(org.eclipse.winery.common.constants.MimeTypes) DirectoryId(org.eclipse.winery.repository.datatypes.ids.elements.DirectoryId) LoggerFactory(org.slf4j.LoggerFactory) ApiParam(io.swagger.annotations.ApiParam) HasType(org.eclipse.winery.model.tosca.HasType) AbstractComponentInstanceWithReferencesResource(org.eclipse.winery.repository.rest.resources._support.AbstractComponentInstanceWithReferencesResource) ArtifactTemplateSourceDirectoryId(org.eclipse.winery.repository.datatypes.ids.elements.ArtifactTemplateSourceDirectoryId) MediaType(javax.ws.rs.core.MediaType) ArtifactTemplateId(org.eclipse.winery.common.ids.definitions.ArtifactTemplateId) BackendUtils(org.eclipse.winery.repository.backend.BackendUtils) Status(javax.ws.rs.core.Response.Status) RepositoryFileReference(org.eclipse.winery.common.RepositoryFileReference) Logger(org.slf4j.Logger) IOException(java.io.IOException) RepositoryFactory(org.eclipse.winery.repository.backend.RepositoryFactory) TArtifactTemplate(org.eclipse.winery.model.tosca.TArtifactTemplate) ArtifactResourcesApiData(org.eclipse.winery.repository.rest.resources.apiData.ArtifactResourcesApiData) List(java.util.List) TExtensibleElements(org.eclipse.winery.model.tosca.TExtensibleElements) ArtifactTemplateFilesDirectoryId(org.eclipse.winery.repository.datatypes.ids.elements.ArtifactTemplateFilesDirectoryId) IEntityTemplateResource(org.eclipse.winery.repository.rest.resources.entitytemplates.IEntityTemplateResource) javax.ws.rs(javax.ws.rs) Response(javax.ws.rs.core.Response) RestUtils(org.eclipse.winery.repository.rest.RestUtils) IHasName(org.eclipse.winery.repository.rest.resources._support.IHasName) PropertiesResource(org.eclipse.winery.repository.rest.resources.entitytemplates.PropertiesResource) InputStream(java.io.InputStream) DirectoryId(org.eclipse.winery.repository.datatypes.ids.elements.DirectoryId) ArtifactTemplateSourceDirectoryId(org.eclipse.winery.repository.datatypes.ids.elements.ArtifactTemplateSourceDirectoryId) ArtifactTemplateFilesDirectoryId(org.eclipse.winery.repository.datatypes.ids.elements.ArtifactTemplateFilesDirectoryId) RepositoryFileReference(org.eclipse.winery.common.RepositoryFileReference) InputStream(java.io.InputStream) ArtifactTemplateSourceDirectoryId(org.eclipse.winery.repository.datatypes.ids.elements.ArtifactTemplateSourceDirectoryId) IOException(java.io.IOException)

Example 8 with DirectoryId

use of org.eclipse.winery.repository.datatypes.ids.elements.DirectoryId in project winery by eclipse.

the class GenericArtifactsResource method generateImplementationArtifact.

/**
 * Generates the implementation artifact using the implementation artifact generator. Also sets the properties
 * according to the requirements of OpenTOSCA.
 */
private Response generateImplementationArtifact(String interfaceName, String javaPackage, UriInfo uriInfo, ArtifactTemplateId artifactTemplateId) {
    assert (this instanceof ImplementationArtifactsResource);
    IRepository repository = RepositoryFactory.getRepository();
    QName type = RestUtils.getType(this.res);
    EntityTypeId typeId = getTypeId(type).orElseThrow(IllegalStateException::new);
    TInterface i = findInterface(typeId, interfaceName).orElseThrow(IllegalStateException::new);
    Path workingDir;
    try {
        workingDir = Files.createTempDirectory("winery");
    } catch (IOException e2) {
        LOGGER.debug("Could not create temporary directory", e2);
        return Response.serverError().entity("Could not create temporary directory").build();
    }
    URI artifactTemplateFilesUri = uriInfo.getBaseUri().resolve(RestUtils.getAbsoluteURL(artifactTemplateId)).resolve("files");
    URL artifactTemplateFilesUrl;
    try {
        artifactTemplateFilesUrl = artifactTemplateFilesUri.toURL();
    } catch (MalformedURLException e2) {
        LOGGER.debug("Could not convert URI to URL", e2);
        return Response.serverError().entity("Could not convert URI to URL").build();
    }
    String name = this.generateName(typeId, interfaceName);
    Generator gen = new Generator(i, javaPackage, artifactTemplateFilesUrl, name, workingDir.toFile());
    Path targetPath;
    try {
        targetPath = gen.generateProject();
    } catch (Exception e) {
        LOGGER.debug("IA generator failed", e);
        return Response.serverError().entity("IA generator failed").build();
    }
    DirectoryId fileDir = new ArtifactTemplateSourceDirectoryId(artifactTemplateId);
    try {
        BackendUtils.importDirectory(targetPath, repository, fileDir);
    } catch (IOException e) {
        throw new WebApplicationException(e);
    }
    // clean up
    FileUtils.forceDelete(workingDir);
    this.storeProperties(artifactTemplateId, typeId, name);
    URI url = uriInfo.getBaseUri().resolve(Util.getUrlPath(artifactTemplateId));
    return Response.created(url).build();
}
Also used : Path(java.nio.file.Path) MalformedURLException(java.net.MalformedURLException) WebApplicationException(javax.ws.rs.WebApplicationException) TInterface(org.eclipse.winery.model.tosca.TInterface) QName(javax.xml.namespace.QName) IOException(java.io.IOException) URI(java.net.URI) URL(java.net.URL) WebApplicationException(javax.ws.rs.WebApplicationException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) ArtifactTemplateSourceDirectoryId(org.eclipse.winery.repository.datatypes.ids.elements.ArtifactTemplateSourceDirectoryId) DirectoryId(org.eclipse.winery.repository.datatypes.ids.elements.DirectoryId) EntityTypeId(org.eclipse.winery.model.ids.definitions.EntityTypeId) ArtifactTemplateSourceDirectoryId(org.eclipse.winery.repository.datatypes.ids.elements.ArtifactTemplateSourceDirectoryId) IRepository(org.eclipse.winery.repository.backend.IRepository) Generator(org.eclipse.winery.generators.ia.Generator)

Example 9 with DirectoryId

use of org.eclipse.winery.repository.datatypes.ids.elements.DirectoryId in project winery by eclipse.

the class BackendUtils method synchronizeReferences.

/**
 * Synchronizes the list of files of the given artifact template with the list of files contained in the given
 * repository. The repository is updated after synchronization.
 * <p>
 * This was intended if a user manually added files in the "files" directory and expected winery to correctly export
 * a CSAR
 *
 * @param repository The repository to search for the files
 * @param id         the id of the artifact template
 * @return The synchronized artifact template. Used for testing only, because mockito cannot mock static methods
 * (https://github.com/mockito/mockito/issues/1013).
 */
public static TArtifactTemplate synchronizeReferences(IRepository repository, ArtifactTemplateId id) throws IOException {
    TArtifactTemplate template = repository.getElement(id);
    List<TArtifactReference> toRemove = new ArrayList<>();
    List<RepositoryFileReference> toAdd = new ArrayList<>();
    List<TArtifactReference> artifactReferences = template.getArtifactReferences();
    DirectoryId fileDir = new ArtifactTemplateFilesDirectoryId(id);
    SortedSet<RepositoryFileReference> files = repository.getContainedFiles(fileDir);
    if (artifactReferences == null) {
        artifactReferences = new ArrayList<>();
        template.setArtifactReferences(artifactReferences);
    }
    determineChanges(artifactReferences, files, toRemove, toAdd);
    if (toAdd.size() > 0 || toRemove.size() > 0) {
        // apply removal list
        toRemove.forEach(artifactReferences::remove);
        // apply addition list
        artifactReferences.addAll(toAdd.stream().map(fileRef -> {
            String path = Util.getUrlPath(fileRef);
            return new TArtifactReference.Builder(path).build();
        }).collect(Collectors.toList()));
        // finally, persist only if something changed
        BackendUtils.persist(repository, id, template);
    }
    return template;
}
Also used : TArtifactTemplate(org.eclipse.winery.model.tosca.TArtifactTemplate) TArtifactReference(org.eclipse.winery.model.tosca.TArtifactReference) ArrayList(java.util.ArrayList) ArtifactTemplateFilesDirectoryId(org.eclipse.winery.repository.datatypes.ids.elements.ArtifactTemplateFilesDirectoryId) ArtifactTemplateFilesDirectoryId(org.eclipse.winery.repository.datatypes.ids.elements.ArtifactTemplateFilesDirectoryId) GenericDirectoryId(org.eclipse.winery.repository.datatypes.ids.elements.GenericDirectoryId) DirectoryId(org.eclipse.winery.repository.datatypes.ids.elements.DirectoryId) RepositoryFileReference(org.eclipse.winery.repository.common.RepositoryFileReference)

Example 10 with DirectoryId

use of org.eclipse.winery.repository.datatypes.ids.elements.DirectoryId in project winery by eclipse.

the class YamlArtifactsSynchronizer method deleteYamlArtifact.

private void deleteYamlArtifact(TNodeTemplate nodeTemplate, TArtifact artifact) throws IOException {
    DirectoryId artifactDirectory = BackendUtils.getYamlArtifactDirectoryOfNodeTemplate(this.serviceTemplateId, nodeTemplate.getId(), artifact.getId());
    repository.forceDelete(artifactDirectory);
}
Also used : DirectoryId(org.eclipse.winery.repository.datatypes.ids.elements.DirectoryId)

Aggregations

DirectoryId (org.eclipse.winery.repository.datatypes.ids.elements.DirectoryId)16 ArtifactTemplateFilesDirectoryId (org.eclipse.winery.repository.datatypes.ids.elements.ArtifactTemplateFilesDirectoryId)7 RepositoryFileReference (org.eclipse.winery.common.RepositoryFileReference)4 RepositoryFileReference (org.eclipse.winery.repository.common.RepositoryFileReference)4 ArtifactTemplateSourceDirectoryId (org.eclipse.winery.repository.datatypes.ids.elements.ArtifactTemplateSourceDirectoryId)4 GenericDirectoryId (org.eclipse.winery.repository.datatypes.ids.elements.GenericDirectoryId)4 IOException (java.io.IOException)3 Path (java.nio.file.Path)3 Map (java.util.Map)3 DefinitionsChildId (org.eclipse.winery.model.ids.definitions.DefinitionsChildId)3 TArtifactReference (org.eclipse.winery.model.tosca.TArtifactReference)3 TArtifactTemplate (org.eclipse.winery.model.tosca.TArtifactTemplate)3 URI (java.net.URI)2 HashMap (java.util.HashMap)2 List (java.util.List)2 ZipOutputStream (java.util.zip.ZipOutputStream)2 ArtifactTemplateId (org.eclipse.winery.common.ids.definitions.ArtifactTemplateId)2 ServiceTemplateId (org.eclipse.winery.model.ids.definitions.ServiceTemplateId)2 TExtensibleElements (org.eclipse.winery.model.tosca.TExtensibleElements)2 BackendUtils (org.eclipse.winery.repository.backend.BackendUtils)2