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

io.lsn.java.common.findable.Findable Maven / Gradle / Ivy

package io.lsn.java.common.findable;

import io.lsn.java.common.exception.NotFoundException;
import io.lsn.java.common.json.mapper.JsonMapper;

import java.lang.reflect.Method;

/**
 * Findable trait - implement it and use automagic method findBy:
 *
 * @example:
 * return findBy(this, "apiToken", token, SystemUser.class);
 *
 * it will invoke "findByApiToken" method on your dao instance and it will try to cast the response to SystemUser.class
 *
 * @author Patryk Szlagowski 
 */
public interface Findable {

    /**
     * return dao instance
     * @return
     */
    Object getDao();

    /**
     * find record by given field
     * NOTE: you have to implement dao method
     *
     * @param thiss
     * @param by
     * @param id
     * @param 
     * @return
     * @throws NotFoundException
     */
    default  T findBy(Object thiss, String by, Object id, Class toClass) throws NotFoundException {
        if (!(thiss instanceof Findable)) {
            throw new NotFoundException(thiss.getClass().getName().concat(" should implement Findable interface"));
        }

        Object dao = ((Findable) thiss).getDao();
        String methodName = "findBy".concat(by.substring(0, 1).toUpperCase().concat(by.substring(1)));
        Method method = null;
        try {
            method = dao.getClass().getMethod(methodName, id.getClass());
        } catch (NoSuchMethodException e) {
            throw new NotFoundException(e.getMessage(), e);
        }

        T found = null;

        try {
            found = JsonMapper.getInstance().mapObjectFromJsonSnakeCase((String) method.invoke(dao, id), toClass);
        } catch (Exception e) {
            throw new NotFoundException(e.getMessage(), e);
        }

        if (found == null) {
            throw new NotFoundException();
        }

        return found;
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy