001package common.http.error;
002
003import common.http.interceptor.HttpServletBiConsumer;
004import common.http.interceptor.ServletInterceptor;
005
006import javax.servlet.ServletException;
007import javax.servlet.http.HttpServletRequest;
008import javax.servlet.http.HttpServletResponse;
009import javax.validation.ConstraintViolation;
010import javax.validation.ConstraintViolationException;
011import java.io.IOException;
012import java.util.Collection;
013import java.util.Collections;
014import java.util.List;
015import java.util.stream.Collectors;
016
017import static javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST;
018
019/**
020 * @see ForwardOnError
021 */
022public class ForwardOnErrorInterceptor extends ServletInterceptor<ForwardOnError> {
023
024    private String page;
025
026    @Override
027    protected void init(ForwardOnError annotation) {
028        this.page = annotation.value();
029    }
030
031    @Override
032    public void handle(HttpServletRequest req, HttpServletResponse resp, HttpServletBiConsumer next) throws ServletException, IOException {
033        try{
034            next.handle(req,resp);
035        } catch (IllegalArgumentException e) {
036            forwardErrorPage(req, resp, SC_BAD_REQUEST, e.getMessage());
037        } catch (ConstraintViolationException e) {
038            List<String> collect = e.getConstraintViolations().stream()
039                    .map(ConstraintViolation::getMessage)
040                    .collect(Collectors.toList());
041            forwardErrorPage(req,resp,SC_BAD_REQUEST,collect);
042        }
043    }
044
045    private void forwardErrorPage(HttpServletRequest req, HttpServletResponse resp,
046                                  int code, Collection<String> messages) throws ServletException, IOException {
047        req.setAttribute("errors", messages);
048        resp.setStatus(code);
049        req.getRequestDispatcher(page).forward(req, resp);
050    }
051
052    private void forwardErrorPage(HttpServletRequest req, HttpServletResponse resp, int code, String message) throws IOException, ServletException {
053        List<String> singleton = message == null ? Collections.emptyList() : List.of(message);
054        forwardErrorPage(req, resp, code, singleton);
055    }
056
057    @Override
058    public int priority() {
059        return 1;
060    }
061}