OwnerEndpoint.java 2.5 KB
Newer Older
1 2 3 4
package at.ac.tuwien.sepm.assignment.individual.endpoint;

import at.ac.tuwien.sepm.assignment.individual.endpoint.dto.OwnerDto;
import at.ac.tuwien.sepm.assignment.individual.endpoint.mapper.OwnerMapper;
5
import at.ac.tuwien.sepm.assignment.individual.entity.Owner;
6 7 8
import at.ac.tuwien.sepm.assignment.individual.exception.NotFoundException;
import at.ac.tuwien.sepm.assignment.individual.service.OwnerService;
import java.lang.invoke.MethodHandles;
9 10

import at.ac.tuwien.sepm.assignment.individual.util.ValidationException;
11 12 13
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
14
import org.springframework.dao.DataAccessException;
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ResponseStatusException;

@RestController
@RequestMapping(OwnerEndpoint.BASE_URL)
public class OwnerEndpoint {

    static final String BASE_URL = "/owners";
    private static final Logger LOGGER = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
    private final OwnerService ownerService;
    private final OwnerMapper ownerMapper;

    @Autowired
    public OwnerEndpoint(OwnerService ownerService, OwnerMapper ownerMapper) {
        this.ownerService = ownerService;
        this.ownerMapper = ownerMapper;
    }

    @GetMapping(value = "/{id}")
    public OwnerDto getOneById(@PathVariable("id") Long id) {
        LOGGER.info("GET " + BASE_URL + "/{}", id);
        try {
            return ownerMapper.entityToDto(ownerService.findOneById(id));
        } catch (NotFoundException e) {
            throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Error during reading owner", e);
        }
    }
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60

    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    public OwnerDto addHorse(@RequestBody OwnerDto owner) {
        LOGGER.info("POST " + BASE_URL);
        try {
            Owner ownerEntity = ownerMapper.dtoToEntity(owner);
            return ownerMapper.entityToDto(ownerService.addOwner(ownerEntity));
        } catch (ValidationException e) {
            LOGGER.error(e.getMessage());
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST,
                "Error during adding new owner: " + e.getMessage());
        } catch (DataAccessException e) {
            LOGGER.error(e.getMessage());
            throw new ResponseStatusException(HttpStatus.UNPROCESSABLE_ENTITY,
                "Something went wrong during the communication with the database");
        }
    }
61
}