br.com.jarch.faces.controller.CrudDataController Maven / Gradle / Ivy
package br.com.jarch.faces.controller;
import br.com.jarch.core.annotation.*;
import br.com.jarch.core.cdi.GlobalInformation;
import br.com.jarch.core.crud.dynamic.*;
import br.com.jarch.core.crud.repository.CrudRepository;
import br.com.jarch.core.crud.service.ICrudService;
import br.com.jarch.core.exception.BaseException;
import br.com.jarch.core.exception.ReflectionException;
import br.com.jarch.core.exception.ValidationException;
import br.com.jarch.faces.util.JavaScriptUtils;
import br.com.jarch.faces.util.JsfUtils;
import br.com.jarch.core.jpa.api.ClientJpqlBuilder;
import br.com.jarch.core.jpa.type.FieldOrder;
import br.com.jarch.core.model.ICrudEntity;
import br.com.jarch.core.model.type.ActionCrudType;
import br.com.jarch.core.util.BundleUtils;
import br.com.jarch.util.LogUtils;
import br.com.jarch.util.ReflectionUtils;
import br.com.jarch.core.type.LoadCrudType;
import org.primefaces.component.commandlink.CommandLink;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.enterprise.event.Event;
import javax.faces.event.AbortProcessingException;
import javax.inject.Inject;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
import java.util.stream.Collectors;
@JArchCrudData
public abstract class CrudDataController, R extends CrudRepository> extends BaseDataController implements ICrudDataController {
private static final String JARCH_BPM_CHECK_FINALIZE_TASK = "jarch.bpm.checkFinalizeTask";
@Inject
@JArchEventDataLoadInsert
private Event eventDataLoadInsert;
@Inject
@JArchEventDataLoadClone
private Event eventDataLoadClone;
@Inject
@JArchEventDataLoadChange
private Event eventDataLoadChange;
@Inject
@JArchEventDataLoadDelete
private Event eventDataLoadDelete;
@Inject
@JArchEventDataCancel
private Event eventDataCancel;
@Inject
@JArchEventDataReturn
private Event eventDataReturn;
@Inject
private Event eventLoadDynamic;
private ActionCrudType actionCrud;
private transient JArchDynamicShowDataController annotationDynamic;
private String idDynamic;
private String labelMenuDynamic;
private boolean firedCancel;
private boolean firedReturn;
private boolean firedSave;
private boolean firedDynamic;
private List fieldDynamics;
private Long idEntityOriginal;
@PostConstruct
private void initCrudDataController() {
startEnviroment();
fillFieldDynamics();
}
@PreDestroy
private void endCrudDataController() {
endEnviroment();
}
@Override
public void startEnviroment() {
try {
configVariablesDataController();
boolean blocked = isStateConsult()
|| isStateDelete()
|| (isStateDynamic() && annotationDynamic != null && annotationDynamic.blockedMaster());
setBlockedMaster(blocked);
setBlockedDetail(blocked);
if (isStateInsert())
insertEnviroment();
else if (isStateClone())
cloneEnviroment(entity);
else if (isStateChange())
changeEnviroment(entity);
else if (isStateConsult())
consultEnviroment(entity);
else if (isStateDelete())
deleteEnviroment(entity);
else if (isStateDynamic())
dynamicEnviroment(entity);
} catch (Exception ex) {
JavaScriptUtils.showMessageHeaderError(ex);
}
}
private void endEnviroment() {
new TransferListToData<>(classEntity()).clear();
}
private void configVariablesDataController() {
TransferListToData transferListToData = new TransferListToData<>(classEntity());
actionCrud = transferListToData.getActionCrud();
Long idEntity = transferListToData.getIdEntity();
entity = transferListToData.getEntity();
annotationDynamic = transferListToData.getAnnotationDynamic();
idDynamic = transferListToData.getIdDynamic();
labelMenuDynamic = transferListToData.getLabelMenuDynamic();
getService().setIdDynamic(idDynamic);
LoadCrudType type = getLoadCrudType(transferListToData);
if (idEntity != null)
entity = getService().loadCrud(idEntity, this.getClass().getSimpleName(), type);
else if (entity != null && entity.getId() != null)
entity = getService().loadCrud(entity.getId(), this.getClass().getSimpleName(), type);
idEntityOriginal = idEntity;
}
private static LoadCrudType getLoadCrudType(TransferListToData transferListToData) {
if (transferListToData.getActionCrud() == null)
return LoadCrudType.ANY;
else if (transferListToData.getActionCrud().isClone())
return LoadCrudType.CLONE;
else if (transferListToData.getActionCrud().isChange())
return LoadCrudType.CHANGE;
else if (transferListToData.getActionCrud().isConsult())
return LoadCrudType.CONSULT;
else if (transferListToData.getActionCrud().isDelete())
return LoadCrudType.DELETE;
else
return LoadCrudType.ANY;
}
@Override
public void insertEnviroment() {
entity = getService().createEntity(this.getClass().getSimpleName());
clearAllDataModelDetail();
eventDataLoadInsert.fire(entity);
AnnotationUtils.processMethodAnnotedIntoInstance(JArchCrudDataStartEnviromentInsert.class, this);
}
@Override
public void cloneEnviroment(E entity) {
this.entity = entity;
clearAllDataModelDetail();
this.entity = getService().cloneEntity(entity);
eventDataLoadClone.fire(entity);
AnnotationUtils.processMethodAnnotedIntoInstance(JArchCrudDataStartEnviromentClone.class, this);
}
@Override
public void changeEnviroment(E entity) {
this.entity = entity;
clearAllDataModelDetail();
eventDataLoadChange.fire(entity);
AnnotationUtils.processMethodAnnotedIntoInstance(JArchCrudDataStartEnviromentChange.class, this);
}
@Override
public void deleteEnviroment(E entity) {
this.entity = entity;
clearAllDataModelDetail();
eventDataLoadDelete.fire(entity);
AnnotationUtils.processMethodAnnotedIntoInstance(JArchCrudDataStartEnviromentDelete.class, this);
}
@Override
public void dynamicEnviroment(E entity) {
this.entity = entity;
clearAllDataModelDetail();
Annotation qualifier = new JArchEventDataLoadDynamicQualifier(idDynamic);
Event eventQualifier = eventLoadDynamic.select(qualifier);
eventQualifier.fire(entity);
AnnotationUtils.processMethodAnnotedIntoInstance(JArchCrudDataStartEnviromentDynamic.class, this);
}
@Override
public void callEndTask() {
try {
validDataDetailDontSave();
GlobalInformation.getInstance().set(JARCH_BPM_CHECK_FINALIZE_TASK, true);
} catch (Exception be) {
JavaScriptUtils.showMessageHeaderError(be);
throw new AbortProcessingException();
}
}
@Override
public void callDontEndTask() {
try {
validDataDetailDontSave();
GlobalInformation.getInstance().set(JARCH_BPM_CHECK_FINALIZE_TASK, false);
} catch (Exception be) {
JavaScriptUtils.showMessageHeaderError(be);
throw new AbortProcessingException();
}
}
@Override
public void callSave() {
firedSave = true;
try {
validDataDetailDontSave();
AnnotationUtils.processMethodAnnotedIntoInstance(JArchCrudDataBeforeSave.class, this);
boolean endTask = GlobalInformation.getInstance().get(JARCH_BPM_CHECK_FINALIZE_TASK, false);
if (isStateInsert()) {
saveInsert();
insertValueDynamics();
} else if (isStateClone()) {
saveClone();
insertValueDynamics();
} else if (isStateChange()) {
entity = saveChange();
changeValueDynamics();
} else if (isStateDynamic()) {
entity = saveDynamic();
changeValueDynamics();
} else if (isStateDelete()) {
saveDelete();
deleteValueDynamics();
}
GlobalInformation.getInstance().set(JARCH_BPM_CHECK_FINALIZE_TASK, endTask);
AnnotationUtils.processMethodAnnotedIntoInstance(JArchCrudDataAfterSave.class, this);
if (isShowMessageSuccess()) {
if (isRedirectPageAfterButtonSave())
JavaScriptUtils.showMessageBodySuccessRedirect(getTitleSuccess(), getDescriptionSuccess(), getPageList());
else
JavaScriptUtils.showMessageBodySuccessNoRedirect(getTitleSuccess(), getDescriptionSuccess());
} else if (isRedirectPageAfterButtonSave())
JsfUtils.redirect(getPageList());
if ((isStateInsert() || isStateClone()) && isReloadEntity()) {
actionCrud = ActionCrudType.CHANGE;
entity = getService().loadCrud(entity.getId());
}
} catch (Exception ex) {
LogUtils.generate(ex);
JavaScriptUtils.showMessageHeaderError(ex);
}
}
@Override
public void saveInsert() {
getService().insert(entity, groupsBeanValidation(), validations());
}
@Override
public void saveClone() {
getService().insert(entity, groupsBeanValidation(), validations());
}
@Override
public E saveChange() {
return getService().change(entity, groupsBeanValidation(), validations());
}
@Override
public E saveDynamic() {
return getService().change(entity, groupsBeanValidation(), validations());
}
@Override
public void saveDelete() {
getService().delete(entity, groupsBeanValidation(), validations());
}
@Override
public ActionCrudType getActionCrud() {
return actionCrud;
}
@Override
public String getLabelAction() {
if (getActionCrud() == null)
return "";
return getActionCrud().isDynamic() ? labelDynamic() : getActionCrud().getDescription();
}
@Override
public String getLabelButtonSave() {
return BundleUtils.messageBundle(isStateDelete() ? "label.excluir" : "label.gravar");
}
@Override
public String getLabelButtonCancel() {
return BundleUtils.messageBundle("label.cancelar");
}
@Override
public String getLabelButtonReturn() {
return BundleUtils.messageBundle("label.voltar");
}
@Override
public boolean isShowButtonCancel() {
return isStateInsert() || isStateClone() || isStateChange() || isStateDelete() || isStateDynamic();
}
@Override
public boolean isShowButtonReturn() {
return isStateConsult();
}
@Override
public boolean isShowButtonSave() {
return isStateInsert() || isStateClone() || isStateChange();
}
@Override
public boolean isShowButtonDelete() {
return isStateDelete();
}
@Override
public void callMethodDynamic() {
callMethodDynamic(getMethodDynamic());
}
@Override
public void callMethodDynamic(String method) {
firedDynamic = true;
try {
if (ReflectionUtils.getMethod(this.getClass(), method, entity.getClass()) == null)
ReflectionUtils.executeMethod(this, method);
else
ReflectionUtils.executeMethod(this, method, entity);
if (isShowMessageSuccess()) {
if (isRedirectPageAfterButtonSave())
JavaScriptUtils.showMessageBodySuccessRedirect(getTitleSuccess(), getDescriptionSuccess(), getPageList());
else
JavaScriptUtils.showMessageBodySuccessNoRedirect(getTitleSuccess(), getDescriptionSuccess());
}
} catch (Exception ex) {
LogUtils.generate(ex);
JavaScriptUtils.showMessageHeaderError(ex);
}
}
@Override
public String getTitleSuccess() {
return BundleUtils.messageBundle("message.procedimentoRealizadoSucesso");
}
@Override
public String getDescriptionSuccess() {
return "";
}
@Override
public void callMethodDynamic(CrudDataDetail dataDetail) {
try {
ReflectionUtils.executeMethod(this, dataDetail.getAnnotationDynamic().methodName(), dataDetail.getEntity());
if (dataDetail.getAnnotationDynamic().showMessageSuccess())
JavaScriptUtils.showMessageBodySuccessNoRedirect(getTitleSuccess(), getDescriptionSuccess());
} catch (Exception ex) {
LogUtils.generate(ex);
JavaScriptUtils.showMessageHeaderError(ex);
}
}
@Override
public void processButtonCancel() {
eventDataCancel.fire(getEntity());
firedCancel = true;
JsfUtils.redirect(getPageList());
}
@Override
public void processButtonReturn() {
eventDataReturn.fire(getEntity());
firedReturn = true;
JsfUtils.redirect(getPageList());
}
@Override
public boolean isStateInsert() {
return getActionCrud() != null && getActionCrud().isInsert();
}
@Override
public boolean isStateClone() {
return getActionCrud() != null && getActionCrud().isClone();
}
@Override
public boolean isStateChange() {
return getActionCrud() != null && getActionCrud().isChange();
}
@Override
public boolean isStateConsult() {
return getActionCrud() != null && getActionCrud().isConsult();
}
@Override
public boolean isStateDelete() {
return getActionCrud() != null && getActionCrud().isDelete();
}
@Override
public boolean isStateDynamic() {
return getActionCrud() != null && getActionCrud().isDynamic();
}
@Override
public CommandLink getCommandLinkDynamicAction() {
if (!getActionCrud().isDynamic())
return null;
if (annotationDynamic == null)
return null;
return GenerateCommandLink.createCommandLink(this,
entity,
annotationDynamic.id(),
annotationDynamic.labelButton(),
annotationDynamic.styleClass(),
annotationDynamic.nameMethodDataController(),
annotationDynamic.evaluateRendered(),
annotationDynamic.evaluateDisabled(),
annotationDynamic.onClick(),
annotationDynamic.onStart(),
annotationDynamic.onError(),
annotationDynamic.onComplete());
}
@Override
public void setCommandLinkDynamicAction(CommandLink commandLink) {
//
}
@Override
public CommandLink getCommandLinkDynamicDontSaveTaskAction() {
if (!getActionCrud().isDynamic())
return null;
if (annotationDynamic == null)
return null;
return GenerateCommandLink.createCommandLink(this,
entity,
annotationDynamic.id(),
annotationDynamic.labelButtonDontEndTask(),
annotationDynamic.styleClass(),
annotationDynamic.nameMethodDataController(),
annotationDynamic.evaluateRendered(),
annotationDynamic.evaluateDisabled(),
annotationDynamic.onClick(),
annotationDynamic.onStart(),
annotationDynamic.onError(),
annotationDynamic.onComplete());
}
@Override
public void setIconDynamicAction(String iconDynamicAction) {
//
}
@Override
public String getIconDynamicAction() {
if (!getActionCrud().isDynamic())
return null;
if (annotationDynamic == null)
return null;
return annotationDynamic.icon();
}
@Override
public void setCommandLinkDynamicDontSaveTaskAction(CommandLink commandLink) {
//
}
@Override
public String getIdDynamicAction() {
return idDynamic;
}
@Override
public String getMethodDynamic() {
return annotationDynamic == null ? null : annotationDynamic.nameMethodDataController();
}
@Override
public boolean isConfirmationDynamic() {
return annotationDynamic.confirmation();
}
@Override
public String getHeaderConfirmationDynamic() {
return BundleUtils.messageBundle(annotationDynamic.headerConfirmation());
}
@Override
public String getMessageConfirmationDynamic() {
return BundleUtils.messageBundle(annotationDynamic.messageConfirmation());
}
@Override
public void blockedMaster() {
setBlockedMaster(true);
}
@Override
public void blockedDetail() {
setBlockedDetail(true);
}
@Override
public void blockedMasterDetail() {
blockedMaster();
blockedDetail();
}
@Override
public void processMethodDynamicDataDetail(CrudDataDetail dataDetail, String idDynamic, E linhaTabela) {
Optional archDynamicMenuDataDetailWithDataAction = getArchDynamicDetailShowDataAction(idDynamic);
if (archDynamicMenuDataDetailWithDataAction.isPresent()) {
dataDetail.dynamic(linhaTabela, archDynamicMenuDataDetailWithDataAction.get());
return;
}
Optional archDynamicMenuDataDetailNoDataAction = getArchDynamicDetailDirectAction(idDynamic);
if (archDynamicMenuDataDetailNoDataAction.isPresent()) {
try {
ReflectionUtils.executeMethod(this, archDynamicMenuDataDetailNoDataAction.get().methodName(), linhaTabela);
} catch (InvocationTargetException | IllegalAccessException ex) {
if (ex.getCause() != null && BaseException.class.isAssignableFrom(ex.getCause().getClass()))
throw new ReflectionException((BaseException) ex.getCause());
throw new ReflectionException(ex);
}
}
}
@Override
public boolean isFiredCancel() {
return firedCancel;
}
@Override
public boolean isFiredReturn() {
return firedReturn;
}
@Override
public boolean isFiredSave() {
return firedSave;
}
@Override
public boolean isFiredDynamic() {
return firedDynamic;
}
public void validDataDetailDontSave() {
List detailsDontSave = new ArrayList<>();
for (Field field : this.getClass().getDeclaredFields()) {
if (CrudDataDetail.class.isAssignableFrom(field.getType())) {
CrudDataDetail> executeMethod = (CrudDataDetail>) ReflectionUtils.getValueByField(this, field);
if (!ActionCrudType.CONSULT.equals(executeMethod.getAction())) {
String nameEntityBundle = executeMethod.getEntity().getClass().getSimpleName().replace("Entity", "");
nameEntityBundle = nameEntityBundle.substring(0, 1).toLowerCase().concat(nameEntityBundle.substring(1));
detailsDontSave.add("label." + nameEntityBundle);
executeMethod.showDataTab();
}
}
}
if (!detailsDontSave.isEmpty()) {
throw new ValidationException(BundleUtils.messageBundleParam("message.dadosPendenteSemSalvar",
detailsDontSave.stream().map(BundleUtils::messageBundle).collect(Collectors.joining(", "))));
}
}
@Override
public List listFieldDynamics(int row) {
if (!isUsageDynamicColumn())
return List.of();
return fieldDynamics
.stream()
.filter(f -> f.getRow() == row)
.sorted(Comparator.comparing(FieldDynamicEntity::getColumn))
.collect(Collectors.toList());
}
@Override
public List getRowsDynamics() {
if (!isUsageDynamicColumn())
return List.of();
return fieldDynamics
.stream()
.map(FieldDynamicEntity::getRow)
.distinct()
.collect(Collectors.toList());
}
@Override
public void reloadEntity() {
entity = getService().loadCrud(entity.getId());
}
@Override
public void updateVersionRegistry() {
Integer version = ClientJpqlBuilder
.newInstance(classEntity())
.select("versionRegister")
.where()
.equalsTo(classEntity(), entity)
.collect()
.single(Integer.class);
entity.setVersionRegister(version);
}
private Optional getArchDynamicDetailShowDataAction(String idDynamic) {
return Arrays
.stream(getClass().getDeclaredFields())
.filter(f -> f.getAnnotationsByType(JArchDynamicDetailShowDataController.class).length > 0)
.flatMap(f -> Arrays.stream(f.getAnnotationsByType(JArchDynamicDetailShowDataController.class)).filter(f2 -> f2.id().equals(idDynamic)))
.findAny();
}
private Optional getArchDynamicDetailDirectAction(String idDynamic) {
return Arrays
.stream(getClass().getDeclaredFields())
.filter(f -> f.getAnnotationsByType(JArchDynamicDetailDirectController.class).length > 0)
.flatMap(f -> Arrays.stream(f.getAnnotationsByType(JArchDynamicDetailDirectController.class)).filter(f2 -> f2.id().equals(idDynamic)))
.findAny();
}
private String labelDynamic() {
if (labelMenuDynamic != null)
return labelMenuDynamic;
if (!annotationDynamic.labelMenu().isEmpty())
return BundleUtils.messageBundle(annotationDynamic.labelMenu());
return ActionCrudType.DYNAMIC.getDescription();
}
private void fillFieldDynamics() {
if (!isUsageDynamicColumn())
return;
String pageAtual = JsfUtils.getOnlyNamePageCurrent();
fieldDynamics = FieldDynamicJpqlBuilder
.newInstance()
.orderBy(FieldOrder.asc("row"), FieldOrder.asc("column"))
.where()
.equalsTo("page", pageAtual)
.collect()
.list();
if (!isStateInsert()) {
for (FieldDynamicEntity fieldDynamic : fieldDynamics) {
ValueDynamicJpqlBuilder
.newInstance()
.where()
.equalsTo("fieldDynamic", fieldDynamic)
.and()
.equalsTo("entityId", idEntityOriginal)
.collect()
.any()
.ifPresent(vd -> fieldDynamic.setValue(vd.getValue()));
}
}
}
private void insertValueDynamics() {
if (!isUsageDynamicColumn() || !isStateInsert())
return;
insertDynamics();
}
private void changeValueDynamics() {
if (!isUsageDynamicColumn() || !isStateChange())
return;
deleteDynamics();
insertDynamics();
}
private void deleteValueDynamics() {
if (!isUsageDynamicColumn())
return;
deleteDynamics();
}
private void deleteDynamics() {
if (!isUsageDynamicColumn() || fieldDynamics.isEmpty())
return;
List valueDynamics = ValueDynamicJpqlBuilder
.newInstance()
.where()
.contains("fieldDynamic", fieldDynamics)
.and()
.equalsTo("entityId", getEntity().getId())
.collect()
.list();
ValueDynamicService.getInstance().delete(valueDynamics);
}
private void insertDynamics() {
if (!isUsageDynamicColumn())
return;
List valueDynamics = new ArrayList<>();
for (FieldDynamicEntity fieldDynamic : fieldDynamics) {
ValueDynamicEntity valueDynamic = ValueDynamicService.getInstance().createEntityFromFieldDynamic(fieldDynamic);
if (fieldDynamic.isBinary())
valueDynamic.setValueBinary(fieldDynamic.getValueBinary());
valueDynamic.setValue(fieldDynamic.getValue());
valueDynamic.setEntityId(getEntity().getId());
valueDynamics.add(valueDynamic);
}
ValueDynamicService.getInstance().insert(valueDynamics);
}
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy