Skip to content

Commit

Permalink
update resources
Browse files Browse the repository at this point in the history
  • Loading branch information
LuciaM1 committed Nov 13, 2023
1 parent 310cbef commit 64f4be8
Show file tree
Hide file tree
Showing 9 changed files with 170 additions and 43 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package it.gov.pagopa.atmlayer.service.model.dto;

import it.gov.pagopa.atmlayer.service.model.enumeration.NoDeployableResourceType;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Pattern;
import jakarta.ws.rs.DefaultValue;
import jakarta.ws.rs.FormParam;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.File;

@Data
@NoArgsConstructor
public class ResourceUpdateDto {

@FormParam("file")
@NotNull(message = "resource file is required")
private File file;
@FormParam("filename")
@NotNull(message = "filename is required")
@Pattern(regexp = "^[a-zA-Z0-9_-]+\\.[a-zA-Z]+$", message = "it must be of form ${regexp}")
private String filename;
@FormParam("resourceType")
@NotNull(message = "resource type is required")
private NoDeployableResourceType resourceType;
}
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,8 @@ public enum AppErrorCodeEnum {
WORKFLOW_RESOURCE_FILE_CANNOT_BE_DEPLOYED("ATMLM_4000026", "The referenced Workflow Resource file can not be deployed", NOT_DEPLOYABLE_STATUS),
RESOURCE_WITH_SAME_NAME_AND_PATH_ALREADY_SAVED("ATMLM_4000027", "A resource with same file name and path already exists", NOT_UPLOADABLE),
INEXISTENT_RESOURCE_CANNOT_BE_UPDATED("ATMLM_4000028","The referenced resource does not exist: cannot be updated",NOT_UPDATABLE),
RESOURCE_WITH_DIFFERENT_STORAGE_KEY_CANNOT_BE_UPDATED("ATMLM_4000029","The referenced resource has a different storage key: cannot be updated",NOT_UPDATABLE);
RESOURCE_WITH_DIFFERENT_STORAGE_KEY_CANNOT_BE_UPDATED("ATMLM_4000029","The referenced resource has a different storage key: cannot be updated",NOT_UPDATABLE),
RESOURCE_DOES_NOT_EXIST("ATMLM_4000024", "The referenced Resource does not exist", NOT_EXISTING_REFERENCED_ENTITY);



Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,10 @@ public Uni<ResourceFile> findByStorageKey(String key){
"select resource from ResourceFile resource where resource.storageKey = :key",
Parameters.with("key", key)).firstResult();
}

public Uni<ResourceFile> findByResourceId(UUID resourceId){
return find(
"select resource from ResourceFile resource where resource.resourceEntity.resourceId = :id",
Parameters.with("id", resourceId)).firstResult();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@
import it.gov.pagopa.atmlayer.service.model.dto.ResourceCreationDto;
import it.gov.pagopa.atmlayer.service.model.entity.ResourceEntity;
import it.gov.pagopa.atmlayer.service.model.mapper.ResourceEntityMapper;
import it.gov.pagopa.atmlayer.service.model.mapper.ResourceFileMapper;
import it.gov.pagopa.atmlayer.service.model.model.ResourceDTO;
import it.gov.pagopa.atmlayer.service.model.model.ResourceFileDTO;
import it.gov.pagopa.atmlayer.service.model.service.ResourceEntityService;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
Expand All @@ -21,6 +23,7 @@
import org.eclipse.microprofile.openapi.annotations.parameters.RequestBody;
import org.eclipse.microprofile.openapi.annotations.tags.Tag;

import java.io.File;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;
Expand All @@ -34,6 +37,8 @@ public class ResourceEntityResource {
@Inject
ResourceEntityMapper resourceEntityMapper;
@Inject
ResourceFileMapper resourceFileMapper;
@Inject
ResourceEntityService resourceEntityService;

@POST
Expand All @@ -50,18 +55,30 @@ public Uni<ResourceDTO> createResource(
.transformToUni(resource -> Uni.createFrom().item(resourceEntityMapper.toDTO(resource)));
}

// @PUT
// @Path("/{uuid}")
// @Consumes(MediaType.MULTIPART_FORM_DATA)
// @Produces(MediaType.APPLICATION_JSON)
// @NonBlocking
// public Uni<ResourceFileDTO> updateResource(@RequestBody(required = true) @Valid ResourceCreationDto resourceCreationDto,
// @PathParam("uuid")UUID uuid) throws NoSuchAlgorithmException, IOException {
// ResourceEntity resourceEntity = resourceEntityMapper.toEntityCreation(resourceCreationDto);
// return resourceEntityService.updateResource(uuid,resourceEntity,resourceCreationDto.getFile(),
// resourceCreationDto.getFilename(),resourceCreationDto.getPath())
// .onItem()
// .transformToUni(updateResourceFile -> Uni.createFrom().item(resourceFileMapper.toDTO(updateResourceFile)));
// }

@PUT
@Path("/{uuid}")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_JSON)
@NonBlocking
public Uni<ResourceDTO> updateResource(@RequestBody(required = true) @Valid ResourceCreationDto resourceCreationDto,
@PathParam("uuid")UUID uuid) throws NoSuchAlgorithmException, IOException {
ResourceEntity resourceEntity = resourceEntityMapper.toEntityCreation(resourceCreationDto);
return resourceEntityService.updateResource(uuid,resourceEntity,resourceCreationDto.getFile(),
resourceCreationDto.getFilename(),resourceCreationDto.getPath())
public Uni<ResourceFileDTO> updateResource(@RequestBody(required = true) File file,
@PathParam("uuid")UUID uuid) {
return resourceEntityService.updateResource(uuid,file)
.onItem()
.transformToUni(resource -> Uni.createFrom().item(resourceEntityMapper.toDTO(resource)));
.transformToUni(updateResourceFile -> Uni.createFrom().item(resourceFileMapper.toDTO(updateResourceFile)));
}


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import it.gov.pagopa.atmlayer.service.model.entity.BpmnVersion;
import it.gov.pagopa.atmlayer.service.model.entity.BpmnVersionPK;
import it.gov.pagopa.atmlayer.service.model.entity.ResourceEntity;
import it.gov.pagopa.atmlayer.service.model.entity.ResourceFile;

import java.io.File;
import java.util.Optional;
Expand All @@ -20,7 +21,11 @@ public interface ResourceEntityService {

Uni<ResourceEntity> saveAndUpload(ResourceEntity resourceEntity, File file, String filename, String path);

Uni<ResourceFile> upload(ResourceEntity resourceEntity, File file, String filename, String path);

Uni<ResourceEntity> createResource(ResourceEntity resourceEntity, File file, String filename,String path);

Uni<ResourceEntity> updateResource (UUID uuid, ResourceEntity newResource,File file, String filename, String path);
//Uni<ResourceFile> updateResource (UUID uuid, ResourceEntity newResource,File file, String filename, String path);

Uni<ResourceFile> updateResource(UUID uuid, File file);
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package it.gov.pagopa.atmlayer.service.model.service;

import io.smallrye.mutiny.Uni;
import it.gov.pagopa.atmlayer.service.model.entity.ResourceEntity;
import it.gov.pagopa.atmlayer.service.model.entity.ResourceFile;

import java.util.Optional;
Expand All @@ -10,4 +11,10 @@ public interface ResourceFileService {
Uni<ResourceFile> save(ResourceFile resourceFile);

Uni<Optional<ResourceFile>> findByStorageKey(String storageKey);

Uni<String> getStorageKey(ResourceEntity resourceEntity);

Uni<String> getCompletePath(ResourceEntity resourceEntity);

Uni<String> getRelativePath(ResourceEntity resourceEntity);
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import it.gov.pagopa.atmlayer.service.model.client.ProcessClient;
import it.gov.pagopa.atmlayer.service.model.entity.BpmnVersionPK;
import it.gov.pagopa.atmlayer.service.model.entity.ResourceEntity;
import it.gov.pagopa.atmlayer.service.model.entity.ResourceFile;
import it.gov.pagopa.atmlayer.service.model.enumeration.AppErrorCodeEnum;
import it.gov.pagopa.atmlayer.service.model.enumeration.S3ResourceTypeEnum;
import it.gov.pagopa.atmlayer.service.model.exception.AtmLayerException;
Expand Down Expand Up @@ -77,19 +78,25 @@ public Uni<Optional<ResourceEntity>> findByUUID(UUID uuid) {
public Uni<ResourceEntity> saveAndUpload(ResourceEntity resourceEntity, File file,
String filename, String path) {
return this.save(resourceEntity)
.onItem().transformToUni(record -> this.resourceEntityStorageService.uploadFile(resourceEntity, file, filename, path)
.onFailure().recoverWithUni(failure -> {
log.error(failure.getMessage());
return Uni.createFrom().failure(new AtmLayerException(
"Failed to save Resource Entity in Object Store. Resource creation aborted",
Response.Status.INTERNAL_SERVER_ERROR, OBJECT_STORE_SAVE_FILE_ERROR));
})
.onItem().transformToUni(record -> upload(resourceEntity, file, filename, path)
.onItem().transformToUni(putObjectResponse -> {
log.info("Completed Resource Entity Creation");
return Uni.createFrom().item(record);
}));
}

@Override
public Uni<ResourceFile> upload(ResourceEntity resourceEntity, File file,
String filename, String path){
return this.resourceEntityStorageService.uploadFile(resourceEntity, file, filename, path)
.onFailure().recoverWithUni(failure -> {
log.error(failure.getMessage());
return Uni.createFrom().failure(new AtmLayerException(
"Failed to save Resource Entity in Object Store. Resource creation aborted",
Response.Status.INTERNAL_SERVER_ERROR, OBJECT_STORE_SAVE_FILE_ERROR));
});
}

@Override
public Uni<ResourceEntity> createResource(ResourceEntity resourceEntity, File file,
String filename, String path) {
Expand Down Expand Up @@ -121,39 +128,51 @@ public Uni<ResourceEntity> createResource(ResourceEntity resourceEntity, File fi
}));
}

@Override
public Uni<ResourceEntity> updateResource (UUID uuid, ResourceEntity newResource,File file,
String filename, String path){
String inputStorageKey= resourceEntityStorageService.calculateStorageKey(newResource.getNoDeployableResourceType(),
path,filename);
// @Override
// public Uni<ResourceFile> updateResource (UUID uuid, ResourceEntity newResource,File file,
// String filename, String path){
// String inputStorageKey= resourceEntityStorageService.calculateStorageKey(newResource.getNoDeployableResourceType(),
// path,filename);
// return this.findByUUID(uuid)
// .onItem().transformToUni(optionalResource -> {
// if (optionalResource.isEmpty()) {
// String errorMessage = String.format("Resource with Id %s does not exist: cannot update", uuid);
// throw new AtmLayerException(errorMessage, Response.Status.BAD_REQUEST, INEXISTENT_RESOURCE_CANNOT_BE_UPDATED);
// }
// return Uni.createFrom().item(optionalResource.get());
// })
// .onItem().transformToUni(resourceToUpdate -> {
// Uni<Boolean> sameStorageKey=resourceFileService.getStorageKey(resourceToUpdate)
// .onItem().transformToUni(persistedStorageKey -> {
// if (!persistedStorageKey.equals(inputStorageKey)) {
// String errorMessage = String.format("Update error: resource with Id %s is saved under different storage key: %s", uuid, persistedStorageKey);
// throw new AtmLayerException(errorMessage, Response.Status.BAD_REQUEST, RESOURCE_WITH_DIFFERENT_STORAGE_KEY_CANNOT_BE_UPDATED);
// }
// return Uni.createFrom().item(true);
// });
// return Uni.createFrom().item(resourceToUpdate);
// })
// .onItem().transformToUni(resourceToUpdate -> {
// newResource.setResourceId(resourceToUpdate.getResourceId());
// return Uni.createFrom().item(newResource);
// })
// .onItem().transformToUni(resource -> upload(resource,file, filename, path));
// }

@Override
public Uni<ResourceFile> updateResource(UUID uuid, File file){
return this.findByUUID(uuid)
.onItem().transformToUni(optionalResource -> {
if (optionalResource.isEmpty()) {
String errorMessage = String.format("Update error: resource with Id %s does not exist", uuid);
String errorMessage = String.format("Resource with Id %s does not exist: cannot update", uuid);
throw new AtmLayerException(errorMessage, Response.Status.BAD_REQUEST, INEXISTENT_RESOURCE_CANNOT_BE_UPDATED);
}
return Uni.createFrom().item(optionalResource.get());
})
.onItem().transformToUni(resourceToUpdate -> {
if (!(resourceToUpdate.getStorageKey()).equals(inputStorageKey)) {
String errorMessage = String.format("Update error: resource with Id %s is saved under different storage key: %s", uuid, resourceToUpdate.getStorageKey());
throw new AtmLayerException(errorMessage, Response.Status.BAD_REQUEST, RESOURCE_WITH_DIFFERENT_STORAGE_KEY_CANNOT_BE_UPDATED);
}
return Uni.createFrom().item(resourceToUpdate);
})
.onItem().transformToUni(resourceToUpdate -> {
newResource.setResourceId(resourceToUpdate.getResourceId());
return Uni.createFrom().item(newResource);
})
.onItem().transformToUni(resource -> saveAndUpload(resource,file, filename, path))
.onItem().transformToUni(updatedResource -> this.findByUUID(updatedResource.getResourceId())
.onItem().transformToUni(optionalResource -> {
if (optionalResource.isEmpty()) {
return Uni.createFrom().failure(
new AtmLayerException("Sync problem on resource creation",
Response.Status.INTERNAL_SERVER_ERROR, ATMLM_500));
}
return Uni.createFrom().item(optionalResource.get());
}));
.onItem().transformToUni(resource ->
resourceFileService.getRelativePath(resource)
.onItem().transformToUni(path -> upload(resource, file, resource.getFileName(), path)));
}


}
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,6 @@ public ResourceEntityStorageServiceImpl(ObjectStoreStrategy objectStoreStrategy,
@Override
public Uni<ResourceFile> uploadFile(ResourceEntity resourceEntity, File file, String filenameWithExtension, String relativePath) {
S3ResourceTypeEnum resourceType = convertEnum(resourceEntity.getNoDeployableResourceType());
String storageKey=calculateStorageKey(resourceEntity.getNoDeployableResourceType(),relativePath,resourceEntity.getFileName());
String finalPath = calculateCompletePath(resourceEntity.getNoDeployableResourceType(),relativePath);
log.info("Requesting to write file {} in Object Store at path {}", file.getName(), finalPath);
Context context = Vertx.currentContext();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,29 @@
import io.quarkus.hibernate.reactive.panache.common.WithSession;
import io.quarkus.hibernate.reactive.panache.common.WithTransaction;
import io.smallrye.mutiny.Uni;
import it.gov.pagopa.atmlayer.service.model.entity.ResourceEntity;
import it.gov.pagopa.atmlayer.service.model.entity.ResourceFile;
import it.gov.pagopa.atmlayer.service.model.exception.AtmLayerException;
import it.gov.pagopa.atmlayer.service.model.properties.ObjectStoreProperties;
import it.gov.pagopa.atmlayer.service.model.repository.ResourceFileRepository;
import it.gov.pagopa.atmlayer.service.model.service.ResourceFileService;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.ws.rs.core.Response;
import org.apache.commons.lang3.StringUtils;

import java.util.Optional;

import static it.gov.pagopa.atmlayer.service.model.enumeration.AppErrorCodeEnum.RESOURCE_DOES_NOT_EXIST;
import static java.lang.String.valueOf;

@ApplicationScoped
public class ResourceFileServiceImpl implements ResourceFileService {

@Inject
ResourceFileRepository resourceFileRepository;
@Inject
ObjectStoreProperties objectStoreProperties;

@Override
@WithTransaction
Expand All @@ -29,4 +39,40 @@ public Uni<Optional<ResourceFile>> findByStorageKey(String storageKey) {
return resourceFileRepository.findByStorageKey(storageKey)
.onItem().transformToUni(resource -> Uni.createFrom().item(Optional.ofNullable(resource)));
}

@Override
@WithSession
public Uni<String> getStorageKey(ResourceEntity resourceEntity) {
return resourceFileRepository.findByResourceId(resourceEntity.getResourceId())
.onItem().transformToUni(resourceFile -> Uni.createFrom().item(Optional.ofNullable(resourceFile)))
.onItem().transformToUni(optionalResourceFile ->{
if(optionalResourceFile.isEmpty()){
throw new AtmLayerException("The referenced resource does not exist: cannot retrieve storage key", Response.Status.BAD_REQUEST, RESOURCE_DOES_NOT_EXIST);
}
return Uni.createFrom().item(optionalResourceFile.get().getStorageKey());
});
}

@Override
@WithSession
public Uni<String> getCompletePath(ResourceEntity resourceEntity){
return getStorageKey(resourceEntity)
.onItem().transform(completePath -> completePath.substring(0,completePath.lastIndexOf("/")));

}

@Override
@WithSession
public Uni<String> getRelativePath(ResourceEntity resourceEntity){
String resourceType=valueOf(resourceEntity.getNoDeployableResourceType());
String basePath=objectStoreProperties.resource().pathTemplate();
String basePathWithoutType=basePath.substring(0,basePath.lastIndexOf("/"));
return getCompletePath(resourceEntity)
.onItem().transform(completeBasePath -> StringUtils.stripEnd(completeBasePath.replace(basePathWithoutType,""),"/"))
.onItem().transform(relativePathWithType -> relativePathWithType.substring(relativePathWithType.indexOf("/")+1)
.replace(resourceType,""))
.onItem().transform(relativePathWithSlash -> relativePathWithSlash.substring(relativePathWithSlash.indexOf("/")+1));
}


}

0 comments on commit 64f4be8

Please sign in to comment.