BaseController.java 6.35 KB
package etunicorn.controller;

import com.fasterxml.jackson.annotation.JsonProperty;
import etunicorn.entity.Permission;
import etunicorn.entity.Session;
import etunicorn.exception.EntityRequestMismatchException;
import etunicorn.exception.NotEnoughDataException;
import etunicorn.exception.ObjectNotFoundException;
import etunicorn.repository.PermissionRepository;
import etunicorn.service.SessionService;
import net.minidev.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.Repository;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RestController;

import javax.persistence.Entity;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * etunicorn-server
 * Copyright © 2017 Le Club Info Polytech Lille
 * Tous droits réservés
 */
@RestController
public class BaseController {

    // Utilités pour merger un request dans une entity
    @Autowired
    Map<String, Repository> repositories;
    // Permettent la vérification de permissions dans les méthodes de controlleur
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private SessionService sessionService;
    @Autowired
    private PermissionRepository permissionRepository;

    protected boolean hasPermission(Permission permission) {
        Session session = sessionService.getSession(request);
        if (session == null || permission == null) {
            return false;
        }
        return session.hasPermission(permission);
    }

    protected boolean hasPermission(String nomPermission) {
        Permission permission = permissionRepository.findByNom(nomPermission);
        return hasPermission(permission);
    }

    // Utilités pour générer des erreurs
    ResponseEntity generateError(HttpStatus status, String message) {
        JSONObject json = new JSONObject();
        json.put("status", status.value());
        json.put("message", message);
        return new ResponseEntity(json, status);
    }

    ResponseEntity generateError(HttpStatus status) {
        return generateError(status, String.format("Erreur de type %d", status.value()));
    }

    ResponseEntity generateError(HttpStatus status, Exception exception, String message) {
        JSONObject json = new JSONObject();
        json.put("status", status.value());
        json.put("message", message);
        json.put("errorMessage", exception.getLocalizedMessage());
        json.put("stacktrace", exception.getStackTrace().toString());
        return new ResponseEntity(json, status);
    }

    ResponseEntity generateError(Exception exception) {
        return generateError(HttpStatus.INTERNAL_SERVER_ERROR, exception, exception.getLocalizedMessage());
    }

    protected Object getEntityFromObject(String className, LinkedHashMap object) throws NotEnoughDataException {
        Object repository = repositories.get(className + "Repository");
        for (Method findMethod : repository.getClass().getMethods()) {
            String findMethodName = findMethod.getName();
            if (findMethodName.startsWith("findBy")) {
                String key = Character.toLowerCase(findMethodName.charAt(6)) + findMethodName.substring(7);
                if (object.containsKey(key)) {
                    try {
                        Object data = object.get(key);
                        return findMethod.invoke(repository, data);
                    } catch (IllegalAccessException e) {
                        continue;
                    } catch (InvocationTargetException e) {
                        continue;
                    }
                } else {
                    continue;
                }
            }
        }
        throw new NotEnoughDataException();
    }

    protected void mergeRequestInEntity(Object request, Object entity) throws EntityRequestMismatchException, NotEnoughDataException, ObjectNotFoundException {
        for (Method getMethode : request.getClass().getMethods()) {
            String getMethodName = getMethode.getName();
            JsonProperty annotation = getMethode.getAnnotation(JsonProperty.class);
            if (getMethodName.startsWith("get") && annotation != null) {
                String fieldName = annotation.value();
                String setMethodName = "s" + getMethodName.substring(1);
                Method setMethode;
                Class fieldClass;
                try {
                    fieldClass = entity.getClass().getMethod(getMethodName).getReturnType();
                    setMethode = entity.getClass().getMethod(setMethodName, fieldClass);
                } catch (NoSuchMethodException e) {
                    throw new EntityRequestMismatchException();
                }
                try {
                    if (getMethode.invoke(request) != null) {
                        Object data = getMethode.invoke(request);
                        if (data.getClass() != fieldClass) {
                            if (fieldClass.getAnnotation(Entity.class) != null) {
                                data = getEntityFromObject(fieldName, (LinkedHashMap) data);
                                if (data == null) {
                                    throw new ObjectNotFoundException();
                                }
                            } else {
                                Constructor constructor = fieldClass.getConstructor(data.getClass());
                                if (constructor != null) {
                                    data = constructor.newInstance(data);
                                }
                            }
                        }
                        setMethode.invoke(entity, data);
                    }
                } catch (IllegalAccessException e) {
                    throw new EntityRequestMismatchException();
                } catch (InvocationTargetException e) {
                    throw new EntityRequestMismatchException();
                } catch (NoSuchMethodException e) {
                    throw new EntityRequestMismatchException();
                } catch (InstantiationException e) {
                    throw new EntityRequestMismatchException();
                }
            }

        }
    }
}