Example usage for org.springframework.dao DataIntegrityViolationException DataIntegrityViolationException

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

Introduction

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

Prototype

public DataIntegrityViolationException(String msg) 

Source Link

Document

Constructor for DataIntegrityViolationException.

Usage

From source file:org.cloudfoundry.identity.uaa.codestore.InMemoryExpiringCodeStore.java

@Override
public ExpiringCode generateCode(String data, Timestamp expiresAt) {
    if (data == null || expiresAt == null) {
        throw new NullPointerException();
    }//from   w w w .  j a v a2 s  . c  o m

    if (expiresAt.getTime() < System.currentTimeMillis()) {
        throw new IllegalArgumentException();
    }

    String code = generator.generate();

    ExpiringCode expiringCode = new ExpiringCode(code, expiresAt, data);

    ExpiringCode duplicate = store.putIfAbsent(code, expiringCode);
    if (duplicate != null) {
        throw new DataIntegrityViolationException("Duplicate code: " + code);
    }

    return expiringCode;
}

From source file:de.kaiserpfalzEdv.office.core.tenants.test.TenantServiceTest.java

@Test(expectedExceptions = TenantAlreadyExistsException.class)
public void testCreateInvalidTenant() throws TenantAlreadyExistsException {
    logMethod("create-tenant-doublet", "Creating an invalid tenant (doublet in database)");

    when(repositoryMock.save(any(TenantDO.class)))
            .thenThrow(new DataIntegrityViolationException("Already exists!"));

    service.create(TENANT);//from w w w  . j  a  v  a  2 s  .  c o m

    verify(repositoryMock).save(any(TenantDO.class));
}

From source file:org.bozzo.ipplan.web.exception.GlobalErrorHandlerTest.java

@Test
public void handleDataIntegrityViolationException_should_return_ApiError() {
    ResponseEntity<ApiError> resp = this.errorHandler
            .handleDataIntegrityViolationException(new DataIntegrityViolationException("error"));
    Assert.assertNotNull(resp);//from w w w . j  av a  2s .  c om
    Assert.assertNotNull(resp.getBody());
    Assert.assertEquals(ApiError.DATA_INTEGRITY_VIOLATION, resp.getBody());
}

From source file:com.surevine.chat.openfire.audit.service.AuditServiceTest.java

/**
 * Tests that the audit method of the {@link AuditService} class correctly
 * handles audit errors.//from w  ww  .  j  a  v  a 2  s  .  co m
 */
@Test(expected = AuditException.class)
public void testAuditException() {
    mockAuditDao.save(auditMessage);
    // Throw any Spring DAO exception that could occur
    expectLastCall().andThrow(new DataIntegrityViolationException("Error"));
    replay(mockAuditDao);
    auditService.audit(auditMessage);
    verify(mockAuditDao);
}

From source file:ch.systemsx.cisd.openbis.generic.server.dataaccess.migration.MigrationStepFrom023To024.java

final static String getNewLocation(final ExternalData externalData, final DatabaseInstance databaseInstance) {
    final String location = externalData.location;
    final int index = location.indexOf('/');
    if (index < 0) {
        throw new DataIntegrityViolationException(
                String.format("No '/' found in location of externa data '%s'.", externalData));
    }//from www  . jav a2 s.  c  om
    final String afterInstance = location.substring(index);
    return INSTANCE_PREFIX + databaseInstance.uuid + afterInstance;
}

From source file:free.fucks.initi.config.data.ExceptionPointCut.java

/**
 *
 * @param joinPoint// www .  j  av  a  2  s.  c om
 * @return
 * @throws Throwable
 */
@Around("execution(* free.fucks.initi.service.*.insert*(..)) || "
        + "execution(* free.fucks.initi.service.*.update*(..)) || "
        + "execution(* free.fucks.initi.service.*.save*(..)) || "
        + "execution(* free.fucks.initi.service.*.remove*(..)) || "
        + "execution(* free.fucks.initi.service.*.delete*(..))")
public Object doHandleDataIntegrityViolationException(ProceedingJoinPoint joinPoint) throws Throwable {
    try {
        LOG.info("------> Caiu no ASPECT!");
        return joinPoint.proceed();
    } catch (DataIntegrityViolationException exception) {
        if (exception.getMostSpecificCause() instanceof PSQLException) {
            PSQLException currentException = (PSQLException) exception.getMostSpecificCause();

            if (currentException.getSQLState().equals(this.DUPLICATED_REGISTER_ERROR)) {
                //manipula a string de exception para pegar o nome do campo duplicado e 
                //gerar uma exception com uma mensagem mais amigavel ao usurio final.
                int start = currentException.getServerErrorMessage().getDetail().indexOf("Key (") + 5;
                int end = currentException.getServerErrorMessage().getDetail().indexOf(")=(");

                String fieldError = currentException.getServerErrorMessage().getDetail().substring(start, end);

                throw new DataIntegrityViolationException(
                        "O campo " + fieldsMessageSource.getMessage(fieldError, null, Locale.getDefault())
                                + " j existe.");
            }
        }
    } catch (AccessDeniedException exception) {
        throw new AccessDeniedException(
                fieldsMessageSource.getMessage(ACCESS_DENIED_EXCEPTION_MESSAGE, null, Locale.getDefault()));
    } catch (Exception exception) {
        return exception;
    }
    return null;
}

From source file:br.fucks.initial.config.data.ExceptionPointCut.java

/**
 *
 * @param joinPoint//from   w  w w .  j  a va 2  s.  com
 * @return
 * @throws Throwable
 */
@Around("execution(* br.org.pti.credential.service.*.insert*(..)) || "
        + "execution(* br.org.pti.credential.service.*.update*(..)) || "
        + "execution(* br.org.pti.credential.service.*.save*(..)) || "
        + "execution(* br.org.pti.credential.service.*.remove*(..)) || "
        + "execution(* br.org.pti.credential.service.*.delete*(..))")
public Object doHandleDataIntegrityViolationException(ProceedingJoinPoint joinPoint) throws Throwable {
    try {
        return joinPoint.proceed();
    } catch (DataIntegrityViolationException exception) {
        if (exception.getMostSpecificCause() instanceof PSQLException) {
            PSQLException currentException = (PSQLException) exception.getMostSpecificCause();

            if (currentException.getSQLState().equals(this.DUPLICATED_REGISTER_ERROR)) {
                //manipula a string de exception para pegar o nome do campo duplicado e 
                //gerar uma exception com uma mensagem mais amigavel ao usurio final.
                int start = currentException.getServerErrorMessage().getDetail().indexOf("Key (") + 5;
                int end = currentException.getServerErrorMessage().getDetail().indexOf(")=(");

                String fieldError = currentException.getServerErrorMessage().getDetail().substring(start, end);

                throw new DataIntegrityViolationException(
                        "O campo " + fieldsMessageSource.getMessage(fieldError, null, Locale.getDefault())
                                + " j existe.");
            }
            if (currentException.getSQLState().equals(this.FOREING_KEY_REFERENCED_ERROR)) {
                //manipula a string de exception para pegar o nome do campo duplicado e 
                //gerar uma exception com uma mensagem mais amigavel ao usurio final.
                int start = currentException.getServerErrorMessage().getDetail().indexOf("table ") + 7;
                int end = currentException.getServerErrorMessage().getDetail().indexOf("\".");

                String fieldReference = currentException.getServerErrorMessage().getMessage().substring(
                        currentException.getServerErrorMessage().getMessage().indexOf("on table \"") + 10,
                        currentException.getServerErrorMessage().getMessage().indexOf("\" violates"));
                String fieldReferenceOn = currentException.getServerErrorMessage().getDetail().substring(start,
                        end);

                throw new DataIntegrityViolationException("No  possvel excluir o <b>"
                        + fieldsMessageSource.getMessage(fieldReference, null, Locale.getDefault())
                        + "</b> pois o registro ainda  referenciado em <b>'"
                        + fieldsMessageSource.getMessage(fieldReferenceOn, null, Locale.getDefault())
                        + "'</b>.");
            }
        }
    } catch (AccessDeniedException exception) {
        throw new AccessDeniedException(
                fieldsMessageSource.getMessage(ACCESS_DENIED_EXCEPTION_MESSAGE, null, Locale.getDefault()));
    } catch (Exception exception) {
        return exception;
    }
    return null;
}

From source file:com.br.helpdesk.controller.UserGroupController.java

@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
public @ResponseBody void delete(@PathVariable Long id)
        throws EntityNotFoundException, DataIntegrityViolationException {
    UserGroup group = service.findById(id);
    if (group == null) {
        throw new EntityNotFoundException();
    }/*  w  ww  .  ja  v a 2s  . c  om*/
    try {
        service.remove(group);
    } catch (Exception e) {
        throw new DataIntegrityViolationException("Entidade possui dependencias e no pode ser deletada");//DEPENDENCIAS
    }
}

From source file:org.impotch.calcul.impot.cantonal.ge.param.dao.ParametreCommunalFichierTxtDao.java

/**************************************************/

protected void traiterLigneFichier(String... tokens) throws ParseException {
    int annee = Integer.parseInt(tokens[0]);
    int noOFS = Integer.parseInt(tokens[1]);
    CleParametre cle = new CleParametre(annee, noOFS);
    if (mapPartPrivilegiee.containsKey(cle))
        throw new DataIntegrityViolationException("Il ne peut pas y avoir plusieurs entres pour l'anne "
                + annee + " et pour la commune N " + noOFS);
    mapPartPrivilegiee.put(cle, new BigDecimal(tokens[2]));
    if (mapCtsAdd.containsKey(cle))
        throw new DataIntegrityViolationException("Il ne peut pas y avoir plusieurs entres pour l'anne "
                + annee + " et pour la commune N " + noOFS);
    mapCtsAdd.put(cle, new BigDecimal(tokens[3]));
}

From source file:com.cubusmail.user.UserAccountDao.java

/**
 * @param name/*  w w  w.jav  a2 s. c  om*/
 * @return
 */
@SuppressWarnings("unchecked")
public UserAccount getUserAccountByUsername(String username) {

    List<UserAccount> list = getHibernateTemplate().find("from UserAccount u where u.username = ?", username);
    if (list.size() == 0) {
        return null;
    } else if (list.size() == 1) {
        UserAccount account = list.get(0);
        if (account.getPreferences() == null) {
            account.setPreferences((Preferences) this.applicationContext.getBean(BeanIds.PREFERENCES_BEAN));
        }
        if (!StringUtils.isEmpty(account.getPreferencesJson())) {
            json2Preferences(account.getPreferencesJson(), account.getPreferences());
        }
        prepareAccount(account);
        return account;
    } else {
        throw new DataIntegrityViolationException("More than one user account for the same username.");
    }
}