All Downloads are FREE. Search and download functionalities are using the official Maven repository.

win.doyto.query.service.AbstractRestController Maven / Gradle / Ivy

// Generated by delombok at Sat Aug 10 11:56:00 CST 2019
package win.doyto.query.service;

import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import win.doyto.query.core.PageQuery;
import win.doyto.query.entity.EntityRequest;
import win.doyto.query.entity.EntityResponse;
import win.doyto.query.entity.Persistable;
import win.doyto.query.validation.CreateGroup;
import win.doyto.query.validation.PageGroup;
import win.doyto.query.validation.PatchGroup;
import win.doyto.query.validation.UpdateGroup;
import java.io.Serializable;
import java.lang.reflect.Constructor;
import java.util.List;

/**
 * AbstractRestController
 *
 * @author f0rb on 2019-05-26
 */
public abstract class AbstractRestController, I extends Serializable, Q extends PageQuery, R extends EntityRequest, S extends EntityResponse> extends AbstractCrudService implements RestService {
    private final S noumenon;

    @SuppressWarnings("unchecked")
    public AbstractRestController() {
        try {
            Class clazz = (Class) getActualTypeArguments()[4];
            Constructor constructor = clazz.getDeclaredConstructor();
            noumenon = constructor.newInstance();
        } catch (final java.lang.Throwable $ex) {
            throw lombok.Lombok.sneakyThrow($ex);
        }
    }

    protected EntityResponse getEntityView() {
        return noumenon;
    }

    protected void checkResult(E e) {
        if (e == null) {
            throw new EntityNotFoundException();
        }
    }

    @GetMapping
    public Object queryOrPage(@Validated(PageGroup.class) Q q) {
        return q.needPaging() ? new PageList<>(list(q), count(q)) : list(q);
    }

    @Override
    public List list(Q q) {
        return query(q, getEntityView()::buildBy);
    }

    @Override
    public PageList page(Q q) {
        return new PageList<>(list(q), count(q));
    }

    @Override
    @GetMapping("{id}")
    public S getById(@PathVariable I id) {
        E e = get(id);
        checkResult(e);
        return getEntityView().buildBy(e);
    }

    @Override
    @DeleteMapping("{id}")
    public void deleteById(@PathVariable I id) {
        checkResult(delete(id));
    }

    @Override
    @PutMapping("{id}")
    public void update(@PathVariable I id, @RequestBody @Validated(UpdateGroup.class) R request) {
        E e = get(id);
        checkResult(e);
        update(request.toEntity(e));
    }

    @Override
    @PatchMapping("{id}")
    public void patch(@PathVariable I id, @RequestBody @Validated(PatchGroup.class) R request) {
        E e = request.toEntity();
        e.setId(id);
        patch(e);
    }

    @Override
    @PostMapping
    public void create(@RequestBody @Validated(CreateGroup.class) R request) {
        save(request.toEntity());
    }
}