argos/dmp-backend/core/src/main/java/eu/eudat/service/supportivematerial/SupportiveMaterialServiceIm...

167 lines
7.7 KiB
Java

package eu.eudat.service.supportivematerial;
import com.fasterxml.jackson.core.JsonProcessingException;
import eu.eudat.authorization.AuthorizationFlags;
import eu.eudat.authorization.Permission;
import eu.eudat.commons.enums.IsActive;
import eu.eudat.convention.ConventionService;
import eu.eudat.data.SupportiveMaterialEntity;
import eu.eudat.model.SupportiveMaterial;
import eu.eudat.model.builder.SupportiveMaterialBuilder;
import eu.eudat.model.deleter.SupportiveMaterialDeleter;
import eu.eudat.model.persist.SupportiveMaterialPersist;
import eu.eudat.query.SupportiveMaterialQuery;
import eu.eudat.service.dmpblueprint.DmpBlueprintServiceImpl;
import gr.cite.commons.web.authz.service.AuthorizationService;
import gr.cite.tools.data.builder.BuilderFactory;
import gr.cite.tools.data.deleter.DeleterFactory;
import gr.cite.tools.data.query.QueryFactory;
import gr.cite.tools.exception.MyApplicationException;
import gr.cite.tools.exception.MyForbiddenException;
import gr.cite.tools.exception.MyNotFoundException;
import gr.cite.tools.exception.MyValidationException;
import gr.cite.tools.fieldset.BaseFieldSet;
import gr.cite.tools.fieldset.FieldSet;
import gr.cite.tools.logging.LoggerService;
import gr.cite.tools.logging.MapLogEntry;
import jakarta.persistence.EntityManager;
import jakarta.xml.bind.JAXBException;
import org.slf4j.LoggerFactory;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import javax.management.InvalidApplicationException;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Instant;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@Service
public class SupportiveMaterialServiceImpl implements SupportiveMaterialService{
private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(DmpBlueprintServiceImpl.class));
private final EntityManager entityManager;
private final AuthorizationService authorizationService;
private final DeleterFactory deleterFactory;
private final BuilderFactory builderFactory;
private final ConventionService conventionService;
private final MessageSource messageSource;
private final QueryFactory queryFactory;
private final SupportiveMaterialCacheService supportiveMaterialCacheService;
public SupportiveMaterialServiceImpl(
EntityManager entityManager, AuthorizationService authorizationService, DeleterFactory deleterFactory, BuilderFactory builderFactory,
ConventionService conventionService, MessageSource messageSource, QueryFactory queryFactory,
SupportiveMaterialCacheService supportiveMaterialCacheService
) {
this.entityManager = entityManager;
this.authorizationService = authorizationService;
this.deleterFactory = deleterFactory;
this.builderFactory = builderFactory;
this.conventionService = conventionService;
this.messageSource = messageSource;
this.queryFactory = queryFactory;
this.supportiveMaterialCacheService = supportiveMaterialCacheService;
}
public ResponseEntity<byte[]> getResponseEntity(String lang, Stream<Path> paths) throws IOException {
List<String> result = paths.filter(Files::isRegularFile)
.map(Path::toString).collect(Collectors.toList());
String fileName = result.stream().filter(about -> about.contains("_" + lang)).findFirst().orElse(null);
if (fileName == null) {
fileName = result.stream().filter(about -> about.contains("_en")).findFirst().get();
}
SupportiveMaterialCacheService.SupportiveMaterialCacheValue supportiveMaterialCacheItem = this.supportiveMaterialCacheService.lookup(this.supportiveMaterialCacheService.buildKey(fileName));
if(supportiveMaterialCacheItem == null){
InputStream is = new FileInputStream(fileName);
// Path path = Paths.get(fileName);
byte[] content = new byte[is.available()];
is.read(content);
is.close();
supportiveMaterialCacheItem = new SupportiveMaterialCacheService.SupportiveMaterialCacheValue(fileName, content);
this.supportiveMaterialCacheService.put(supportiveMaterialCacheItem);
}
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentLength(supportiveMaterialCacheItem.getContent().length);
responseHeaders.setContentType(MediaType.TEXT_HTML);
responseHeaders.set("Content-Disposition", "attachment;filename=" + fileName);
responseHeaders.set("Access-Control-Expose-Headers", "Content-Disposition");
responseHeaders.get("Access-Control-Expose-Headers").add("Content-Type");
return new ResponseEntity<>(supportiveMaterialCacheItem.getContent(), responseHeaders, HttpStatus.OK);
}
// public void persist(SupportiveMaterialPersist model) throws IOException {
// this.supportiveMaterialCacheService.evict(model.getName());
// OutputStream os = new FileOutputStream(model.getName());
// os.write(model.getHtml().getBytes());
// os.close();
// }
public SupportiveMaterial persist(SupportiveMaterialPersist model, FieldSet fields) throws MyForbiddenException, MyValidationException, MyApplicationException, MyNotFoundException, InvalidApplicationException, JAXBException{
logger.debug(new MapLogEntry("persisting data").And("model", model).And("fields", fields));
this.authorizationService.authorizeForce(Permission.EditSupportiveMaterial);
Boolean isUpdate = this.conventionService.isValidGuid(model.getId());
SupportiveMaterialEntity data;
if (isUpdate) {
data = this.entityManager.find(SupportiveMaterialEntity.class, model.getId());
if (data == null)
throw new MyNotFoundException(messageSource.getMessage("General_ItemNotFound", new Object[]{model.getId(), SupportiveMaterial.class.getSimpleName()}, LocaleContextHolder.getLocale()));
} else {
List<SupportiveMaterialEntity> datas = this.queryFactory.query(SupportiveMaterialQuery.class).authorize(AuthorizationFlags.OwnerOrPermission).languageCodes(model.getLanguageCode()).types(model.getType()).collect();
if(datas != null && !datas.isEmpty()){
throw new MyApplicationException("Could not create a new Data with same type and lang code !");
}
data = new SupportiveMaterialEntity();
data.setId(UUID.randomUUID());
data.setIsActive(IsActive.Active);
data.setCreatedAt(Instant.now());
}
data.setType(model.getType());
data.setLanguageCode(model.getLanguageCode());
data.setPayload(model.getPayload());
data.setUpdatedAt(Instant.now());
if (isUpdate) this.entityManager.merge(data);
else this.entityManager.persist(data);
this.entityManager.flush();
return this.builderFactory.builder(SupportiveMaterialBuilder.class).authorize(AuthorizationFlags.OwnerOrPermission).build(BaseFieldSet.build(fields, SupportiveMaterial._id), data);
}
public void deleteAndSave(UUID id) throws MyForbiddenException, InvalidApplicationException {
logger.debug("deleting : {}", id);
this.authorizationService.authorizeForce(Permission.DeleteSupportiveMaterial);
this.deleterFactory.deleter(SupportiveMaterialDeleter.class).deleteAndSaveByIds(List.of(id));
}
}