Untitled
unknown
java
a year ago
2.2 kB
1
Indexable
Never
package sk.emm.portal.validation; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Component; import sk.emm.portal.service.errors.BadRequestAlertException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Map; import java.util.Objects; @Component public class DtoIdValidator { private final Logger log = LoggerFactory.getLogger(DtoIdValidator.class); private static final String INVALID_ID = "Invalid id"; private static final Map<String, String> ENTITY_NAMES = Map.of( "AgendaMappingDTO", "agendaMapping", "AttachmentDTO", "attachment", "AdSyncLogDTO", "adSyncLog", "B2bServicePrivilegeDTO", "b2bService", "B2bServiceDTO", "b2bService", "CompanyInfoDTO", "companyInfo", "ServicePrivilegeDTO", "servicePrivilege", "TopMenuDTO", "topMenu"); public void validate(Object object, Long id, JpaRepository<?, Long> repository) { Class<?> dtoClass = object.getClass(); Long dtoId = getId(object, dtoClass); String entityName = ENTITY_NAMES.get(dtoClass.getSimpleName()); if (Objects.isNull(dtoId) || Objects.isNull(id)) { throw new BadRequestAlertException(INVALID_ID, entityName, "idnull"); } if (!id.equals(dtoId)) { throw new BadRequestAlertException(INVALID_ID, entityName, "idinvalid"); } if (!repository.existsById(id)) { throw new BadRequestAlertException("Entity not found", entityName, "idnotfound"); } } private Long getId(Object object, Class<?> clazz) { Method method; Long result; try { method = clazz.getMethod("getId"); result = (Long) method.invoke(object); return result; } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException exception) { log.error("Could not invoke method getId on object " + clazz.getSimpleName(), exception); } return null; } }