argos/dmp-backend/web/src/main/java/eu/eudat/controllers/v2/SupportiveMaterialControlle...

66 lines
2.8 KiB
Java

package eu.eudat.controllers.v2;
import eu.eudat.authorization.Permission;
import eu.eudat.commons.enums.SupportiveMaterialFieldType;
import eu.eudat.logic.managers.MetricsManager;
import eu.eudat.model.persist.UserGuidePersist;
import eu.eudat.models.data.helpers.responses.ResponseItem;
import eu.eudat.service.supportivematerial.SupportiveMaterialService;
import eu.eudat.types.ApiMessageCode;
import gr.cite.commons.web.authz.service.AuthorizationService;
import org.apache.commons.lang3.EnumUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Objects;
import java.util.stream.Stream;
import static eu.eudat.types.Authorities.ADMIN;
@RestController
@RequestMapping(path = {"/api/material"})
public class SupportiveMaterialController {
private Environment environment;
private SupportiveMaterialService supportiveMaterialService;
private final AuthorizationService authorizationService;
@Autowired
public SupportiveMaterialController(Environment environment, SupportiveMaterialService supportiveMaterialService, MetricsManager metricsManager, AuthorizationService authorizationService) {
this.environment = environment;
this.supportiveMaterialService = supportiveMaterialService;
this.authorizationService = authorizationService;
}
@GetMapping("{lang}")
public ResponseEntity<byte[]> getMaterial(@PathVariable(name = "lang") String lang, String field) throws IOException {
if( !EnumUtils.isValidEnum(SupportiveMaterialFieldType.class, field)){
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
try (Stream<Path> paths = Files.walk(Paths.get(Objects.requireNonNull(this.environment.getProperty(field +".path"))))) {
return this.supportiveMaterialService.getResponseEntity(lang, paths);
}
}
@PostMapping("current")
public @ResponseBody
ResponseEntity<ResponseItem<String>> persist(@RequestBody UserGuidePersist guide, String field) throws IOException {
this.authorizationService.authorizeForce(Permission.AdminRole);
if( !EnumUtils.isValidEnum(SupportiveMaterialFieldType.class, field)){
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
String fileName = this.environment.getProperty(field+ ".path") + guide.getName();
this.supportiveMaterialService.persist(guide, fileName);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<String>().status(ApiMessageCode.SUCCESS_MESSAGE).message("Updated").payload("Updated"));
}
}