Search in sources :

Example 11 with FileContent

use of org.eclipse.vorto.repository.core.FileContent in project vorto by eclipse.

the class ModelRepositoryController method getModelImage.

@ApiOperation(value = "Returns the image of a vorto model")
@ApiResponses(value = { @ApiResponse(code = 400, message = "Wrong input"), @ApiResponse(code = 404, message = "Model not found") })
@GetMapping("/{modelId:.+}/images")
public void getModelImage(@ApiParam(value = "The modelId of vorto model, e.g. com.mycompany.Car:1.0.0", required = true) @PathVariable final String modelId, @ApiParam(value = "Response", required = true) final HttpServletResponse response) {
    Objects.requireNonNull(modelId, "modelId must not be null");
    final ModelId modelID = ModelId.fromPrettyFormat(modelId);
    IModelRepository modelRepo = getModelRepository(modelID);
    // first searches by "display image" tag
    List<Attachment> imageAttachments = modelRepo.getAttachmentsByTag(modelID, Attachment.TAG_DISPLAY_IMAGE);
    // if none present, searches just by "image" tag (for backwards compatibility)
    if (imageAttachments.isEmpty()) {
        imageAttachments = modelRepo.getAttachmentsByTag(modelID, Attachment.TAG_IMAGE);
    }
    // still nope
    if (imageAttachments.isEmpty()) {
        response.setStatus(404);
        return;
    }
    // fetches the first element: either it's the only one (if the display image tag is present)
    // or arbitrarily the first image found (for backwards compatibility)
    Optional<FileContent> imageContent = modelRepo.getAttachmentContent(modelID, imageAttachments.get(0).getFilename());
    if (!imageContent.isPresent()) {
        response.setStatus(404);
        return;
    }
    try {
        response.setHeader(CONTENT_DISPOSITION, ATTACHMENT_FILENAME + modelID.getName() + ".png");
        response.setContentType(APPLICATION_OCTET_STREAM);
        IOUtils.copy(new ByteArrayInputStream(imageContent.get().getContent()), response.getOutputStream());
        response.flushBuffer();
    } catch (IOException e) {
        throw new GenericApplicationException("Error copying file.", e);
    }
}
Also used : IModelRepository(org.eclipse.vorto.repository.core.IModelRepository) FileContent(org.eclipse.vorto.repository.core.FileContent) ByteArrayInputStream(java.io.ByteArrayInputStream) Attachment(org.eclipse.vorto.repository.core.Attachment) IOException(java.io.IOException) GenericApplicationException(org.eclipse.vorto.repository.web.GenericApplicationException) ModelId(org.eclipse.vorto.model.ModelId) GetMapping(org.springframework.web.bind.annotation.GetMapping) ApiOperation(io.swagger.annotations.ApiOperation) ApiResponses(io.swagger.annotations.ApiResponses)

Example 12 with FileContent

use of org.eclipse.vorto.repository.core.FileContent in project vorto by eclipse.

the class ModelRepositoryController method getModelsAndDependencies.

private Map<ModelInfo, FileContent> getModelsAndDependencies(Collection<ModelId> modelIds) {
    Map<ModelInfo, FileContent> modelsMap = new HashMap<>();
    if (modelIds != null && !modelIds.isEmpty()) {
        for (ModelId modelId : modelIds) {
            IModelRepository modelRepo = getModelRepository(modelId);
            ModelInfo modelInfo = modelRepo.getById(modelId);
            Optional<FileContent> modelContent = modelRepo.getFileContent(modelId, Optional.empty());
            if (modelContent.isPresent()) {
                modelsMap.put(modelInfo, modelContent.get());
                modelsMap.putAll(getModelsAndDependencies(modelInfo.getReferences()));
            }
        }
    }
    return modelsMap;
}
Also used : FileContent(org.eclipse.vorto.repository.core.FileContent) IModelRepository(org.eclipse.vorto.repository.core.IModelRepository) ModelInfo(org.eclipse.vorto.repository.core.ModelInfo) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) ModelId(org.eclipse.vorto.model.ModelId)

Example 13 with FileContent

use of org.eclipse.vorto.repository.core.FileContent in project vorto by eclipse.

the class ModelRepositoryController method uploadModelImage.

@PostMapping("/{modelId:.+}/images")
@PreAuthorize("hasAuthority('sysadmin') or " + "hasPermission(T(org.eclipse.vorto.model.ModelId).fromPrettyFormat(#modelId)," + "T(org.eclipse.vorto.repository.core.PolicyEntry.Permission).MODIFY)")
public ResponseEntity<AttachResult> uploadModelImage(@ApiParam(value = "The image to upload", required = true) @RequestParam("file") MultipartFile file, @ApiParam(value = "The model ID of vorto model, e.g. com.mycompany.Car:1.0.0", required = true) @PathVariable final String modelId) {
    LOGGER.info("uploadImage: [" + file.getOriginalFilename() + ", " + file.getSize() + "]");
    ModelId actualModelID = ModelId.fromPrettyFormat(modelId);
    if (!attachmentValidator.validateAttachmentSize(file.getSize())) {
        return new ResponseEntity<>(AttachResult.fail(actualModelID, file.getOriginalFilename(), String.format("The attachment is too large. Maximum size allowed is %dMB", attachmentValidator.getMaxFileSizeSetting())), HttpStatus.PAYLOAD_TOO_LARGE);
    }
    try {
        IUserContext user = UserContext.user(SecurityContextHolder.getContext().getAuthentication(), getWorkspaceId(modelId));
        getModelRepository(actualModelID).attachFile(actualModelID, new FileContent(file.getOriginalFilename(), file.getBytes()), user, Attachment.TAG_IMAGE, Attachment.TAG_DISPLAY_IMAGE);
    } catch (IOException e) {
        throw new GenericApplicationException("error in attaching file to model '" + modelId + "'", e);
    }
    return new ResponseEntity<>(AttachResult.success(actualModelID, file.getOriginalFilename()), HttpStatus.CREATED);
}
Also used : FileContent(org.eclipse.vorto.repository.core.FileContent) IUserContext(org.eclipse.vorto.repository.core.IUserContext) ResponseEntity(org.springframework.http.ResponseEntity) IOException(java.io.IOException) GenericApplicationException(org.eclipse.vorto.repository.web.GenericApplicationException) ModelId(org.eclipse.vorto.model.ModelId) PostMapping(org.springframework.web.bind.annotation.PostMapping) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize)

Example 14 with FileContent

use of org.eclipse.vorto.repository.core.FileContent in project vorto by eclipse.

the class AbstractRepositoryController method addModelToZip.

protected void addModelToZip(ZipOutputStream zipOutputStream, ModelId modelId) throws Exception {
    try {
        FileContent modelFile = getModelRepository(modelId).getFileContent(modelId, Optional.empty()).get();
        ModelInfo modelResource = getModelRepository(modelId).getById(modelId);
        try {
            ZipEntry zipEntry = new ZipEntry(modelResource.getId().getPrettyFormat() + modelResource.getType().getExtension());
            zipOutputStream.putNextEntry(zipEntry);
            zipOutputStream.write(modelFile.getContent());
            zipOutputStream.closeEntry();
        } catch (Exception ex) {
        // entry possible exists already, so skipping TODO: ugly hack!!
        }
        for (ModelId reference : modelResource.getReferences()) {
            addModelToZip(zipOutputStream, reference);
        }
    } catch (NotAuthorizedException notAuthorized) {
        return;
    }
}
Also used : FileContent(org.eclipse.vorto.repository.core.FileContent) ModelInfo(org.eclipse.vorto.repository.core.ModelInfo) ZipEntry(java.util.zip.ZipEntry) NotAuthorizedException(org.eclipse.vorto.repository.web.core.exceptions.NotAuthorizedException) GenerationException(org.eclipse.vorto.repository.plugin.generator.GenerationException) ModelNotFoundException(org.eclipse.vorto.repository.core.ModelNotFoundException) ModelAlreadyExistsException(org.eclipse.vorto.repository.core.ModelAlreadyExistsException) NotAuthorizedException(org.eclipse.vorto.repository.web.core.exceptions.NotAuthorizedException) IOException(java.io.IOException) ValidationException(org.eclipse.vorto.repository.core.impl.validation.ValidationException) NewNamespacesNotSupersetException(org.eclipse.vorto.repository.tenant.NewNamespacesNotSupersetException) ModelId(org.eclipse.vorto.model.ModelId)

Aggregations

FileContent (org.eclipse.vorto.repository.core.FileContent)14 ByteArrayInputStream (java.io.ByteArrayInputStream)8 ModelInfo (org.eclipse.vorto.repository.core.ModelInfo)8 IOException (java.io.IOException)7 ModelId (org.eclipse.vorto.model.ModelId)4 DependencyManager (org.eclipse.vorto.repository.core.impl.utils.DependencyManager)4 ArrayList (java.util.ArrayList)3 ZipEntry (java.util.zip.ZipEntry)3 IModelRepository (org.eclipse.vorto.repository.core.IModelRepository)3 GenericApplicationException (org.eclipse.vorto.repository.web.GenericApplicationException)3 ModelWorkspaceReader (org.eclipse.vorto.utilities.reader.ModelWorkspaceReader)3 HashMap (java.util.HashMap)2 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)2 IUserContext (org.eclipse.vorto.repository.core.IUserContext)2 ModelAlreadyExistsException (org.eclipse.vorto.repository.core.ModelAlreadyExistsException)2 ModelResource (org.eclipse.vorto.repository.core.ModelResource)2 ValidationException (org.eclipse.vorto.repository.core.impl.validation.ValidationException)2 BulkUploadException (org.eclipse.vorto.repository.web.core.exceptions.BulkUploadException)2 NotAuthorizedException (org.eclipse.vorto.repository.web.core.exceptions.NotAuthorizedException)2 ApiOperation (io.swagger.annotations.ApiOperation)1