HorseEndpoint.java 7.62 KB
Newer Older
1 2 3 4 5 6
package at.ac.tuwien.sepm.assignment.individual.endpoint;

import at.ac.tuwien.sepm.assignment.individual.endpoint.dto.HorseDto;
import at.ac.tuwien.sepm.assignment.individual.endpoint.mapper.HorseMapper;
import at.ac.tuwien.sepm.assignment.individual.entity.Horse;
import at.ac.tuwien.sepm.assignment.individual.exception.NotFoundException;
7
import at.ac.tuwien.sepm.assignment.individual.exception.PersistenceException;
8 9 10 11 12 13
import at.ac.tuwien.sepm.assignment.individual.service.HorseService;
import at.ac.tuwien.sepm.assignment.individual.util.ValidationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
14
import org.springframework.http.MediaType;
15
import org.springframework.web.bind.annotation.*;
16
import org.springframework.web.multipart.MultipartFile;
17 18
import org.springframework.web.server.ResponseStatusException;

19
import java.io.IOException;
20
import java.lang.invoke.MethodHandles;
21 22
import java.util.List;
import java.util.Map;
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44

@RestController
@RequestMapping(at.ac.tuwien.sepm.assignment.individual.endpoint.HorseEndpoint.BASE_URL)
public class HorseEndpoint {

    static final String BASE_URL = "/horses";
    private static final Logger LOGGER = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
    private final HorseService horseService;
    private final HorseMapper horseMapper;

    @Autowired
    public HorseEndpoint(HorseService horseService, HorseMapper horseMapper) {
        this.horseService = horseService;
        this.horseMapper = horseMapper;
    }

    @GetMapping(value = "/{id}")
    public HorseDto getOneById(@PathVariable("id") Long id) {
        LOGGER.info("GET " + BASE_URL + "/{}", id);
        try {
            return horseMapper.entityToDto(horseService.findOneById(id));
        } catch (NotFoundException e) {
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
            throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Error during reading horse");
        }
    }

    @GetMapping
    @ResponseStatus(HttpStatus.OK)
    public List<HorseDto> getAll(@RequestParam Map<String, String> filters) {
        try {
            if(filters.isEmpty()) {
                LOGGER.info("GET " + BASE_URL);
                return horseMapper.entityListToDtoList(horseService.getAll());
            } else {
                LOGGER.info("GET " + BASE_URL + "/ with filters" + filters.entrySet());
                return horseMapper.entityListToDtoList(horseService.getFiltered(filters));
            }
        } catch (NotFoundException e) {
            LOGGER.error(e.getMessage());
            throw new ResponseStatusException(HttpStatus.NOT_FOUND, "No horses found");
        } catch (ValidationException e) {
            LOGGER.error(e.getMessage());
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "The request contains filters with bad values: " + e.getMessage());
66 67 68 69 70 71 72 73 74 75 76 77
        }
    }

    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    public HorseDto addHorse(@RequestBody HorseDto horse) {
        LOGGER.info("POST " + BASE_URL);
        try {
            Horse horseEntity = horseMapper.dtoToEntity(horse);
            return horseMapper.entityToDto(horseService.addHorse(horseEntity));
        } catch (ValidationException e) {
            LOGGER.error(e.getMessage());
78
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST,
79
                "Error during adding new horse: " + e.getMessage());
80
        } catch (PersistenceException e) {
81 82
            LOGGER.error(e.getMessage());
            throw new ResponseStatusException(HttpStatus.UNPROCESSABLE_ENTITY,
83
                "Something went wrong during the communication with the database");
84 85 86 87 88 89 90 91 92 93 94 95 96 97
        }
    }

    @PutMapping(value = "/{id}")
    @ResponseStatus(HttpStatus.OK)
    public HorseDto updateHorse(@PathVariable("id") Long id, @RequestBody HorseDto horse) {
        LOGGER.info("PUT " + BASE_URL + "/{}", id);
        try {
            Horse horseEntity = horseMapper.dtoToEntity(horse);
            horseEntity.setId(id);
            return horseMapper.entityToDto((horseService.updateHorse(horseEntity)));
        } catch (ValidationException e) {
            LOGGER.error(e.getMessage());
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST,
98
                "Error during updating horse with id " + id + ": " + e.getMessage());
99
        } catch (PersistenceException e) {
100 101
            LOGGER.error(e.getMessage());
            throw new ResponseStatusException(HttpStatus.UNPROCESSABLE_ENTITY,
102 103 104 105 106
                "Something went wrong during the communication with the database");
        } catch (IOException e) {
            LOGGER.error(e.getMessage());
            throw new ResponseStatusException(HttpStatus.PARTIAL_CONTENT,
                "Operation completed with errors: image could not be saved");
107 108 109 110
        } catch (NotFoundException e) {
            LOGGER.error(e.getMessage());
            throw new ResponseStatusException(HttpStatus.NOT_FOUND,
                "The horse requested could not be found");
111 112 113 114 115 116 117 118 119
        }
    }

    @DeleteMapping(value = "/{id}")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public void deleteHorse(@PathVariable("id") Long id) {
        LOGGER.info("DELETE " + BASE_URL + "/{}", id);
        try {
            horseService.deleteHorse(id);
120
        } catch (PersistenceException e) {
121 122 123 124 125 126 127 128 129 130
            LOGGER.error(e.getMessage());
            throw new ResponseStatusException(HttpStatus.UNPROCESSABLE_ENTITY,
                "Something went wrong during the communication with the database");
        } catch (NotFoundException e) {
            LOGGER.error(e.getMessage());
            throw new ResponseStatusException(HttpStatus.NOT_FOUND,
                "The requested horse has not been found");
        } catch (IOException e) {
            // Log the error and return as it does not concern the user
            LOGGER.error(e.getMessage());
131 132
        }
    }
133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149

    @PostMapping(value = "/upload")
    @ResponseStatus(HttpStatus.CREATED)
    public void addImage(@RequestParam("file") MultipartFile image) {
        LOGGER.info("POST " + BASE_URL + "/upload");
        try {
            horseService.saveImage(image);
        } catch(ValidationException e) {
            LOGGER.error(e.getMessage());
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST,
                "Unsupported file type provided. Supported file types are jpg and png.");
        } catch (IOException e) {
            LOGGER.error(e.getMessage());
            throw new ResponseStatusException(HttpStatus.UNPROCESSABLE_ENTITY,
                "Something went wrong while uploading the file");
        }
    }
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169

    @RequestMapping(value = "/image/{path}", produces = {MediaType.IMAGE_JPEG_VALUE,MediaType.IMAGE_PNG_VALUE}, method=RequestMethod.GET)
    @ResponseStatus(HttpStatus.OK)
    public @ResponseBody byte[] getImage(@PathVariable("path") String path) {
        // Get the image as byte array and return it with a media type assigned
        // https://www.baeldung.com/spring-controller-return-image-file
        // https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/http/MediaType.html
        LOGGER.info("GET " + BASE_URL + "/image/{}", path);
        try {
            return horseService.getImage(path);
        } catch(ValidationException e) {
            LOGGER.error(e.getMessage());
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST,
                "Unsupported file type provided. Supported file types are jpg and png.");
        } catch (IOException e) {
            LOGGER.error(e.getMessage());
            throw new ResponseStatusException(HttpStatus.NOT_FOUND,
                "Something went wrong while reading the file");
        }
    }
170
}