Example usage for org.springframework.dao DataIntegrityViolationException getMostSpecificCause

List of usage examples for org.springframework.dao DataIntegrityViolationException getMostSpecificCause

Introduction

In this page you can find the example usage for org.springframework.dao DataIntegrityViolationException getMostSpecificCause.

Prototype

public Throwable getMostSpecificCause() 

Source Link

Document

Retrieve the most specific cause of this exception, that is, either the innermost cause (root cause) or this exception itself.

Usage

From source file:com.gst.useradministration.service.AppUserWritePlatformServiceJpaRepositoryImpl.java

@Transactional
@Override/*w ww.j a  v a  2s.  com*/
@Caching(evict = { @CacheEvict(value = "users", allEntries = true),
        @CacheEvict(value = "usersByUsername", allEntries = true) })
public CommandProcessingResult createUser(final JsonCommand command) {

    try {
        this.context.authenticatedUser();

        this.fromApiJsonDeserializer.validateForCreate(command.json());

        final String officeIdParamName = "officeId";
        final Long officeId = command.longValueOfParameterNamed(officeIdParamName);

        final Office userOffice = this.officeRepositoryWrapper.findOneWithNotFoundDetection(officeId);

        final String[] roles = command.arrayValueOfParameterNamed("roles");
        final Set<Role> allRoles = assembleSetOfRoles(roles);

        AppUser appUser;

        final String staffIdParamName = "staffId";
        final Long staffId = command.longValueOfParameterNamed(staffIdParamName);

        Staff linkedStaff = null;
        if (staffId != null) {
            linkedStaff = this.staffRepositoryWrapper.findByOfficeWithNotFoundDetection(staffId,
                    userOffice.getId());
        }

        Collection<Client> clients = null;
        if (command.hasParameter(AppUserConstants.IS_SELF_SERVICE_USER)
                && command.booleanPrimitiveValueOfParameterNamed(AppUserConstants.IS_SELF_SERVICE_USER)
                && command.hasParameter(AppUserConstants.CLIENTS)) {
            JsonArray clientsArray = command.arrayOfParameterNamed(AppUserConstants.CLIENTS);
            Collection<Long> clientIds = new HashSet<>();
            for (JsonElement clientElement : clientsArray) {
                clientIds.add(clientElement.getAsLong());
            }
            clients = this.clientRepositoryWrapper.findAll(clientIds);
        }

        appUser = AppUser.fromJson(userOffice, linkedStaff, allRoles, clients, command);

        final Boolean sendPasswordToEmail = command.booleanObjectValueOfParameterNamed("sendPasswordToEmail");
        this.userDomainService.create(appUser, sendPasswordToEmail);

        return new CommandProcessingResultBuilder() //
                .withCommandId(command.commandId()) //
                .withEntityId(appUser.getId()) //
                .withOfficeId(userOffice.getId()) //
                .build();
    } catch (final DataIntegrityViolationException dve) {
        handleDataIntegrityIssues(command, dve.getMostSpecificCause(), dve);
        return CommandProcessingResult.empty();
    } catch (final PersistenceException | AuthenticationServiceException dve) {
        Throwable throwable = ExceptionUtils.getRootCause(dve.getCause());
        handleDataIntegrityIssues(command, throwable, dve);
        return new CommandProcessingResultBuilder() //
                .withCommandId(command.commandId()) //
                .build();
    } catch (final PlatformEmailSendException e) {
        final List<ApiParameterError> dataValidationErrors = new ArrayList<>();

        final String email = command.stringValueOfParameterNamed("email");
        final ApiParameterError error = ApiParameterError.parameterError("error.msg.user.email.invalid",
                "The parameter email is invalid.", "email", email);
        dataValidationErrors.add(error);

        throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist",
                "Validation errors exist.", dataValidationErrors);
    }
}

From source file:com.gst.useradministration.service.RoleWritePlatformServiceJpaRepositoryImpl.java

/**
 * Method for Enabling the role//  ww  w  . java2s  .com
 */
@Transactional
@Override
public CommandProcessingResult enableRole(Long roleId) {
    try {
        /**
         * Checking the role present in DB or not using role_id
         */
        final Role role = this.roleRepository.findOne(roleId);
        if (role == null) {
            throw new RoleNotFoundException(roleId);
        }
        //if(!role.isEnabled()){throw new RoleNotFoundException(roleId);}

        role.enableRole();
        this.roleRepository.save(role);
        return new CommandProcessingResultBuilder().withEntityId(roleId).build();

    } catch (final DataIntegrityViolationException e) {
        throw new PlatformDataIntegrityException("error.msg.unknown.data.integrity.issue",
                "Unknown data integrity issue with resource: " + e.getMostSpecificCause());
    }
}

From source file:com.gst.useradministration.service.AppUserWritePlatformServiceJpaRepositoryImpl.java

@Transactional
@Override/*from  ww  w  .j  a va 2  s .c  o m*/
@Caching(evict = { @CacheEvict(value = "users", allEntries = true),
        @CacheEvict(value = "usersByUsername", allEntries = true) })
public CommandProcessingResult updateUser(final Long userId, final JsonCommand command) {

    try {

        this.context.authenticatedUser(new CommandWrapperBuilder().updateUser(null).build());

        this.fromApiJsonDeserializer.validateForUpdate(command.json());

        final AppUser userToUpdate = this.appUserRepository.findOne(userId);

        if (userToUpdate == null) {
            throw new UserNotFoundException(userId);
        }

        final AppUserPreviousPassword currentPasswordToSaveAsPreview = getCurrentPasswordToSaveAsPreview(
                userToUpdate, command);

        Collection<Client> clients = null;
        boolean isSelfServiceUser = userToUpdate.isSelfServiceUser();
        if (command.hasParameter(AppUserConstants.IS_SELF_SERVICE_USER)) {
            isSelfServiceUser = command
                    .booleanPrimitiveValueOfParameterNamed(AppUserConstants.IS_SELF_SERVICE_USER);
        }

        if (isSelfServiceUser && command.hasParameter(AppUserConstants.CLIENTS)) {
            JsonArray clientsArray = command.arrayOfParameterNamed(AppUserConstants.CLIENTS);
            Collection<Long> clientIds = new HashSet<>();
            for (JsonElement clientElement : clientsArray) {
                clientIds.add(clientElement.getAsLong());
            }
            clients = this.clientRepositoryWrapper.findAll(clientIds);
        }

        final Map<String, Object> changes = userToUpdate.update(command, this.platformPasswordEncoder, clients);

        if (changes.containsKey("officeId")) {
            final Long officeId = (Long) changes.get("officeId");
            final Office office = this.officeRepositoryWrapper.findOneWithNotFoundDetection(officeId);
            userToUpdate.changeOffice(office);
        }

        if (changes.containsKey("staffId")) {
            final Long staffId = (Long) changes.get("staffId");
            Staff linkedStaff = null;
            if (staffId != null) {
                linkedStaff = this.staffRepositoryWrapper.findByOfficeWithNotFoundDetection(staffId,
                        userToUpdate.getOffice().getId());
            }
            userToUpdate.changeStaff(linkedStaff);
        }

        if (changes.containsKey("roles")) {
            final String[] roleIds = (String[]) changes.get("roles");
            final Set<Role> allRoles = assembleSetOfRoles(roleIds);

            userToUpdate.updateRoles(allRoles);
        }

        if (!changes.isEmpty()) {
            this.appUserRepository.saveAndFlush(userToUpdate);

            if (currentPasswordToSaveAsPreview != null) {
                this.appUserPreviewPasswordRepository.save(currentPasswordToSaveAsPreview);
            }

        }

        return new CommandProcessingResultBuilder() //
                .withEntityId(userId) //
                .withOfficeId(userToUpdate.getOffice().getId()) //
                .with(changes) //
                .build();
    } catch (final DataIntegrityViolationException dve) {
        handleDataIntegrityIssues(command, dve.getMostSpecificCause(), dve);
        return CommandProcessingResult.empty();
    } catch (final PersistenceException | AuthenticationServiceException dve) {
        Throwable throwable = ExceptionUtils.getRootCause(dve.getCause());
        handleDataIntegrityIssues(command, throwable, dve);
        return new CommandProcessingResultBuilder() //
                .withCommandId(command.commandId()) //
                .build();
    }
}

From source file:com.gst.useradministration.service.RoleWritePlatformServiceJpaRepositoryImpl.java

/**
 * Method for Delete Role/*from   w w  w  .j  a v a  2 s. c o m*/
 */
@Transactional
@Override
public CommandProcessingResult deleteRole(Long roleId) {

    try {
        /**
         * Checking the role present in DB or not using role_id
         */
        final Role role = this.roleRepository.findOne(roleId);
        if (role == null) {
            throw new RoleNotFoundException(roleId);
        }

        /**
         * Roles associated with users can't be deleted
         */
        final Integer count = this.roleRepository.getCountOfRolesAssociatedWithUsers(roleId);
        if (count > 0) {
            throw new RoleAssociatedException("error.msg.role.associated.with.users.deleted", roleId);
        }

        this.roleRepository.delete(role);
        return new CommandProcessingResultBuilder().withEntityId(roleId).build();
    } catch (final DataIntegrityViolationException e) {
        throw new PlatformDataIntegrityException("error.msg.unknown.data.integrity.issue",
                "Unknown data integrity issue with resource: " + e.getMostSpecificCause());
    }
}

From source file:com.gst.useradministration.service.RoleWritePlatformServiceJpaRepositoryImpl.java

/**
 * Method for disabling the role//from   ww w  .java2s  . com
 */
@Transactional
@Override
public CommandProcessingResult disableRole(Long roleId) {
    try {
        /**
         * Checking the role present in DB or not using role_id
         */
        final Role role = this.roleRepository.findOne(roleId);
        if (role == null) {
            throw new RoleNotFoundException(roleId);
        }
        //if(role.isDisabled()){throw new RoleNotFoundException(roleId);}

        /**
         * Roles associated with users can't be disable
         */
        final Integer count = this.roleRepository.getCountOfRolesAssociatedWithUsers(roleId);
        if (count > 0) {
            throw new RoleAssociatedException("error.msg.role.associated.with.users.disabled", roleId);
        }

        /**
         * Disabling the role
         */
        role.disableRole();
        this.roleRepository.save(role);
        return new CommandProcessingResultBuilder().withEntityId(roleId).build();

    } catch (final DataIntegrityViolationException e) {
        throw new PlatformDataIntegrityException("error.msg.unknown.data.integrity.issue",
                "Unknown data integrity issue with resource: " + e.getMostSpecificCause());
    }
}

From source file:com.gst.infrastructure.hooks.service.HookWritePlatformServiceJpaRepositoryImpl.java

@Transactional
@Override/*from w w  w .  j  a  va2  s .  c om*/
@CacheEvict(value = "hooks", allEntries = true)
public CommandProcessingResult deleteHook(final Long hookId) {

    this.context.authenticatedUser();
    final Hook hook = retrieveHookBy(hookId);
    try {
        this.hookRepository.delete(hook);
    } catch (final DataIntegrityViolationException e) {
        throw new PlatformDataIntegrityException("error.msg.unknown.data.integrity.issue",
                "Unknown data integrity issue with resource: " + e.getMostSpecificCause());
    }
    return new CommandProcessingResultBuilder().withEntityId(hookId).build();
}

From source file:com.gst.organisation.teller.service.TellerWritePlatformServiceJpaImpl.java

@Override
@Transactional//from w  ww  .j  a  va 2s. com
public CommandProcessingResult deleteCashierAllocation(Long tellerId, Long cashierId, JsonCommand command) {
    try {
        final AppUser currentUser = this.context.authenticatedUser();
        final Cashier cashier = validateUserPriviledgeOnCashierAndRetrieve(currentUser, tellerId, cashierId);
        this.cashierRepository.delete(cashier);

    } catch (final DataIntegrityViolationException dve) {
        handleTellerDataIntegrityIssues(command, dve.getMostSpecificCause(), dve);
        return CommandProcessingResult.empty();
    } catch (final PersistenceException dve) {
        Throwable throwable = ExceptionUtils.getRootCause(dve.getCause());
        handleTellerDataIntegrityIssues(command, throwable, dve);
        return CommandProcessingResult.empty();
    }

    return new CommandProcessingResultBuilder() //
            .withEntityId(cashierId) //
            .build();
}

From source file:com.gst.infrastructure.reportmailingjob.service.ReportMailingJobWritePlatformServiceImpl.java

/** 
 * Handle any SQL data integrity issue //w w w . j  a  v  a  2  s.c  o  m
 *
 * @param jsonCommand -- JsonCommand object
 * @param dve -- data integrity exception object
 * @return None
 **/
private void handleDataIntegrityIssues(final JsonCommand jsonCommand,
        final DataIntegrityViolationException dve) {
    final Throwable realCause = dve.getMostSpecificCause();

    if (realCause.getMessage().contains(ReportMailingJobConstants.NAME_PARAM_NAME)) {
        final String name = jsonCommand.stringValueOfParameterNamed(ReportMailingJobConstants.NAME_PARAM_NAME);
        throw new PlatformDataIntegrityException("error.msg.report.mailing.job.duplicate.name",
                "Report mailing job with name `" + name + "` already exists",
                ReportMailingJobConstants.NAME_PARAM_NAME, name);
    }

    logger.error(dve.getMessage(), dve);

    throw new PlatformDataIntegrityException("error.msg.charge.unknown.data.integrity.issue",
            "Unknown data integrity issue with resource: " + realCause.getMessage());
}

From source file:com.gst.organisation.teller.service.TellerWritePlatformServiceJpaImpl.java

@Override
@Transactional//from  ww  w .jav  a 2  s .  c o  m
public CommandProcessingResult createTeller(JsonCommand command) {
    try {
        this.context.authenticatedUser();

        final Long officeId = command.longValueOfParameterNamed("officeId");

        this.fromApiJsonDeserializer.validateForCreateAndUpdateTeller(command.json());

        // final Office parent =
        // validateUserPriviledgeOnOfficeAndRetrieve(currentUser, officeId);
        final Office tellerOffice = this.officeRepositoryWrapper.findOneWithNotFoundDetection(officeId);
        final Teller teller = Teller.fromJson(tellerOffice, command);

        // pre save to generate id for use in office hierarchy
        this.tellerRepositoryWrapper.save(teller);

        return new CommandProcessingResultBuilder() //
                .withCommandId(command.commandId()) //
                .withEntityId(teller.getId()) //
                .withOfficeId(teller.getOffice().getId()) //
                .build();
    } catch (final DataIntegrityViolationException dve) {
        handleTellerDataIntegrityIssues(command, dve.getMostSpecificCause(), dve);
        return CommandProcessingResult.empty();
    } catch (final PersistenceException dve) {
        Throwable throwable = ExceptionUtils.getRootCause(dve.getCause());
        handleTellerDataIntegrityIssues(command, throwable, dve);
        return CommandProcessingResult.empty();
    }
}

From source file:com.gst.organisation.teller.service.TellerWritePlatformServiceJpaImpl.java

@Override
@Transactional/*  ww w  . ja v  a2 s  . c o  m*/
public CommandProcessingResult modifyTeller(Long tellerId, JsonCommand command) {
    try {

        final Long officeId = command.longValueOfParameterNamed("officeId");
        final Office tellerOffice = this.officeRepositoryWrapper.findOneWithNotFoundDetection(officeId);
        final AppUser currentUser = this.context.authenticatedUser();

        this.fromApiJsonDeserializer.validateForCreateAndUpdateTeller(command.json());

        final Teller teller = validateUserPriviledgeOnTellerAndRetrieve(currentUser, tellerId);

        final Map<String, Object> changes = teller.update(tellerOffice, command);

        if (!changes.isEmpty()) {
            this.tellerRepositoryWrapper.saveAndFlush(teller);
        }

        return new CommandProcessingResultBuilder() //
                .withCommandId(command.commandId()) //
                .withEntityId(teller.getId()) //
                .withOfficeId(teller.officeId()) //
                .with(changes) //
                .build();
    } catch (final DataIntegrityViolationException dve) {
        handleTellerDataIntegrityIssues(command, dve.getMostSpecificCause(), dve);
        return CommandProcessingResult.empty();
    } catch (final PersistenceException dve) {
        Throwable throwable = ExceptionUtils.getRootCause(dve.getCause());
        handleTellerDataIntegrityIssues(command, throwable, dve);
        return CommandProcessingResult.empty();
    }
}