Example usage for org.hibernate.exception ConstraintViolationException getSQLException

List of usage examples for org.hibernate.exception ConstraintViolationException getSQLException

Introduction

In this page you can find the example usage for org.hibernate.exception ConstraintViolationException getSQLException.

Prototype

public SQLException getSQLException() 

Source Link

Document

Get the underlying SQLException .

Usage

From source file:br.edu.ifrs.restinga.sgru.persistencia.ClienteDAO.java

/**
 * Persiste um objeto Cliente no banco de dados
 * @param cliente O cliente a ser cadastrado no sistema
 * @throws br.edu.ifrs.restinga.sgru.excessao.DadoPessoaInvalidoException Caso a matrcula ou o login informado j esteja cadastrado no sistema
 *///w  w  w.java2 s .  c  o m
public void salvar(Cliente cliente) throws DadoPessoaInvalidoException {
    try {
        sessao.saveOrUpdate(cliente);
    } catch (ConstraintViolationException e) {
        if (e.getSQLException().getMessage().contains("matricula")) {
            sessao.clear();
            throw new DadoPessoaInvalidoException("Matrcula j cadastrada!");
        } else if (e.getSQLException().getMessage().contains("login")) {
            sessao.clear();
            throw new DadoPessoaInvalidoException("Login j cadastrado!");
        } else {

        }
    }
}

From source file:br.edu.ifrs.restinga.sgru.persistencia.FuncionarioDAO.java

/**
 * Persiste um objeto Funcionario no banco de dados
 * @param funcionario /*from w ww .  j a v  a 2 s  .  c o m*/
 * @throws br.edu.ifrs.restinga.sgru.excessao.DadoPessoaInvalidoException Caso a matrcula ou o login informado j esteja cadastrado no sistema
 */
public void salvar(Funcionario funcionario) throws DadoPessoaInvalidoException {
    try {
        sessao.saveOrUpdate(funcionario);
    } catch (ConstraintViolationException e) {
        if (e.getSQLException().getMessage().contains("matricula")) {
            sessao.clear();
            throw new DadoPessoaInvalidoException("Matrcula j cadastrada!");
        } else if (e.getSQLException().getMessage().contains("login")) {
            sessao.clear();
            throw new DadoPessoaInvalidoException("Login j cadastrado!");
        } else {

        }
    }
}

From source file:com.autentia.common.util.ExceptionUtils.java

License:Open Source License

/** 
 * Parsea el mensaje que informa de la causa de una excepcin del tipo ConstraintViolationException, para devolver una clave que obtener del fichero de mensajes.
 * Caused by: java.sql.BatchUpdateException: Cannot delete or update a parent row: a foreign key constraint fails (`acer/securitygroupimpl_grantedauthorityimpl`, CONSTRAINT `FK44EEEBA8D5BA4045` FOREIGN KEY (`authorities_id`) REFERENCES `grantedauthorityimpl` (`id`))
 * @param e ConstraintViolationException
 * @return una clave del tipo REFERENCE_grantedauthorityimpl
 *//* w ww.  j  av  a  2s  . com*/
public static String getReferenceKey(ConstraintViolationException e) {
    String result;
    try {

        final String msg = e.getSQLException().getMessage();
        result = msg.substring(msg.lastIndexOf(MESSAGE_SRTIP_KEY) + MESSAGE_SRTIP_KEY.length(),
                msg.lastIndexOf("(")).replaceAll("`", "").trim();
    } catch (Throwable t) {
        result = "";
    }
    return result;
}

From source file:com.cgi.poc.dw.exception.mapper.CustomSQLConstraintViolationExceptionMapper.java

@Override
public Response toResponse(ConstraintViolationException exception) {
    Response response;/*  w ww .j a  v  a2 s  .  c  om*/
    ErrorInfo errRet = new ErrorInfo();
    String errorString = GeneralErrors.CONSTRAINT_VIOLATION.getMessage().replace("REPLACE",
            exception.getConstraintName());
    errRet.addError(GeneralErrors.CONSTRAINT_VIOLATION.getCode(),
            errorString + ": " + exception.getSQLException().getMessage());

    response = Response.noContent().status(Response.Status.BAD_REQUEST).entity(errRet).build();

    return response;
}

From source file:com.dell.asm.asmcore.asmmanager.db.DeviceConfigureDAO.java

License:Open Source License

/**
 * Create DeviceConfigure./*  w  w  w .  java2  s  .  c  om*/
 * 
 * @param deviceConfigure
 * @return the DeviceConfigureEntity
 */
public DeviceConfigureEntity createDeviceConfigure(DeviceConfigureEntity deviceConfigure)
        throws AsmManagerCheckedException {

    Session session = null;
    Transaction tx = null;

    // Save the device in the db.
    try {
        session = _dao._database.getNewSession();
        tx = session.beginTransaction();
        session.save(deviceConfigure);
        GregorianCalendar now = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
        deviceConfigure.setCreatedDate(now);
        deviceConfigure.setCreatedBy(_dao.extractUserFromRequest());
        // Commit transaction.
        tx.commit();
    } catch (ConstraintViolationException cve) {
        logger.warn("Caught exception during deviceConfigure entity creation: " + cve);
        try {
            if (tx != null) {
                tx.rollback();
            }
        } catch (Exception ex) {
            logger.warn("Unable to rollback transaction during deviceConfigure entity creation: " + ex);
        }
        if (cve.getConstraintName().contains("id")) {
            // throw new
            // AsmManagerDAOException(AsmManagerDAOException.REASON_CODE.DUPLICATE_JOBID,
            // cve);
            throw new AsmManagerCheckedException(AsmManagerCheckedException.REASON_CODE.DUPLICATE_JOBID,
                    AsmManagerMessages.duplicateRefId(cve.getSQLException().getMessage()));
        }
    } catch (Exception e) {
        logger.warn("Caught exception during deviceConfigure creation: " + e);
        try {
            if (tx != null) {
                tx.rollback();
            }
        } catch (Exception ex) {
            logger.warn("Unable to rollback transaction during create deviceConfigure: " + ex);
        }

        throw new AsmManagerInternalErrorException("Error Creating deviceConfigure entity",
                "DeviceConfigureDAO", e);
    } finally {
        try {
            if (session != null) {
                session.close();
            }
        } catch (Exception ex) {
            logger.warn("Unable to close session during create device configure: " + ex);
        }
    }

    return deviceConfigure;
}

From source file:com.dell.asm.asmcore.asmmanager.db.DeviceDiscoverDAO.java

License:Open Source License

/**
 * Create DeviceDiscover./*from ww  w .  java  2 s .c o  m*/
 * 
 * @param deviceDiscover
 * @return the DeviceDiscoverEntity
 */
public DeviceDiscoverEntity createDeviceDiscover(DeviceDiscoverEntity deviceDiscover)
        throws AsmManagerCheckedException {

    Session session = null;
    Transaction tx = null;

    // Save the device in the db.
    try {
        session = _dao._database.getNewSession();
        tx = session.beginTransaction();
        GregorianCalendar now = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
        deviceDiscover.setCreatedDate(now);
        deviceDiscover.setCreatedBy(_dao.extractUserFromRequest());
        session.save(deviceDiscover);
        // Commit transaction.
        tx.commit();
    } catch (ConstraintViolationException cve) {
        logger.warn("Caught exception during DeviceDiscover entity creation: " + cve);
        try {
            if (tx != null) {
                tx.rollback();
            }
        } catch (Exception ex) {
            logger.warn("Unable to rollback transaction during device discover entity creation: " + ex);
        }
        if (cve.getConstraintName().contains("id")) {
            // throw new
            // AsmManagerDAOException(AsmManagerDAOException.REASON_CODE.DUPLICATE_JOBID,
            // cve);
            throw new AsmManagerCheckedException(AsmManagerCheckedException.REASON_CODE.DUPLICATE_JOBID,
                    AsmManagerMessages.duplicateRefId(cve.getSQLException().getMessage()));
        }
    } catch (Exception e) {
        logger.warn("Caught exception during deviceDiscover creation: " + e);
        try {
            if (tx != null) {
                tx.rollback();
            }
        } catch (Exception ex) {
            logger.warn("Unable to rollback transaction during create deviceDiscover: " + ex);
        }

        throw new AsmManagerInternalErrorException("Error Creating deviceDiscover entity", "DeviceDiscoverDAO",
                e);
    } finally {
        try {
            if (session != null) {
                session.close();
            }
        } catch (Exception ex) {
            logger.warn("Unable to close session during create device discover: " + ex);
        }
    }

    return deviceDiscover;
}

From source file:com.dell.asm.asmcore.asmmanager.db.DeviceGroupDAO.java

License:Open Source License

/**
 * Create Device Group /*from   w  w  w  .j av a  2s .co  m*/
 * 
 * @param entity - device group entity
 * 
 * @return entity - device group entity
 *
 * @throws AsmManagerCheckedException
 */
public DeviceGroupEntity createGroupDevice(DeviceGroupEntity entity) throws AsmManagerCheckedException {

    Session session = null;
    Transaction tx = null;
    DeviceGroupEntity duplicateEntity = null;

    try {
        duplicateEntity = getDeviceGroupByName(entity.getName());
    } catch (AsmManagerCheckedException ex) {
        logger.warn("Device Group with same name doesnt exists: " + ex);
    }

    if (null != duplicateEntity) {
        throw new AsmManagerCheckedException(AsmManagerCheckedException.REASON_CODE.DUPLICATE_RECORD,
                AsmManagerMessages.duplicateDeviceGroupName(entity.getName()));
    }

    // Save the device in the db.
    try {
        session = _dao._database.getNewSession();
        tx = session.beginTransaction();

        logger.info("Creating device group in inventory: ");
        entity.setCreatedDate(new GregorianCalendar());
        entity.setUpdatedDate(new GregorianCalendar());
        entity.setCreatedBy(_dao.extractUserFromRequest());
        entity.setUpdatedBy(_dao.extractUserFromRequest());

        if (null == entity.getDeviceInventories())
            entity.setDeviceInventories(new ArrayList<DeviceInventoryEntity>());

        if (null == entity.getGroupsUsers())
            entity.setGroupsUsers(new HashSet<Long>());

        session.save(entity);

        // Commit transaction.
        tx.commit();
    } catch (ConstraintViolationException cve) {
        logger.warn("Caught exception during device group creation: " + cve);
        try {
            if (tx != null) {
                tx.rollback();
            }
        } catch (Exception ex) {
            logger.warn("Unable to rollback transaction during create device group: " + ex);
        }
        if (cve.getConstraintName().contains("seqId")) {
            throw new AsmManagerCheckedException(AsmManagerCheckedException.REASON_CODE.DUPLICATE_REFID,
                    AsmManagerMessages.duplicateRefId(cve.getSQLException().getMessage()));
        } else {
            throw new AsmManagerCheckedException(AsmManagerCheckedException.REASON_CODE.DUPLICATE_RECORD,
                    AsmManagerMessages.duplicateRecord(cve.getSQLException().getMessage()));
        }
    } catch (Exception e) {
        logger.warn("Caught exception during device group inventory creation: " + e);
        try {
            if (tx != null) {
                tx.rollback();
            }
        } catch (Exception ex) {
            logger.warn("Unable to rollback transaction during create device group: " + ex);
        }
        throw new AsmManagerInternalErrorException("Create device group", "DeviceGroupDAO", e);
    } finally {
        try {
            if (session != null) {
                session.close();
            }
        } catch (Exception ex) {
            logger.warn("Unable to close session during create device group: " + ex);
        }
    }

    return entity;
}

From source file:com.dell.asm.asmcore.asmmanager.db.DeviceInventoryDAO.java

License:Open Source License

public DeviceInventoryEntity createDeviceInventoryForDiscoveryFailed(DeviceInventoryEntity device)
        throws AsmManagerCheckedException {

    Session session = null;/*from   w ww .ja  va2s.c o  m*/
    Transaction tx = null;

    // Save the device in the db.
    try {
        session = _dao._database.getNewSession();
        tx = session.beginTransaction();

        logger.info("Creating device in inventory: " + device.getRefId());

        device.setCreatedDate(new GregorianCalendar());
        device.setDiscoveredDate(new GregorianCalendar());
        device.setCreatedBy(_dao.extractUserFromRequest());
        device.setState(DeviceState.DISCOVERY_FAILED);
        session.save(device);

        // Commit transaction.
        tx.commit();
    } catch (ConstraintViolationException cve) {
        logger.warn("Caught exception during device inventory creation: " + cve);
        try {
            if (tx != null) {
                tx.rollback();
            }
        } catch (Exception ex) {
            logger.warn("Unable to rollback transaction during create device: " + ex);
        }
        if (cve.getConstraintName().contains("refid")) {
            throw new AsmManagerCheckedException(AsmManagerCheckedException.REASON_CODE.DUPLICATE_REFID,
                    AsmManagerMessages.duplicateRefId(cve.getSQLException().getMessage()));
        } else if (cve.getConstraintName().contains("service_tag")) {
            throw new AsmManagerCheckedException(AsmManagerCheckedException.REASON_CODE.DUPLICATE_SERVICETAG,
                    AsmManagerMessages.duplicateServiceTag(cve.getSQLException().getMessage()));
        } else {
            throw new AsmManagerCheckedException(AsmManagerCheckedException.REASON_CODE.DUPLICATE_RECORD,
                    AsmManagerMessages.duplicateRecord(cve.getSQLException().getMessage()));
        }
    } catch (Exception e) {
        logger.warn("Caught exception during device inventory creation: " + e);
        try {
            if (tx != null) {
                tx.rollback();
            }
        } catch (Exception ex) {
            logger.warn("Unable to rollback transaction during create device: " + ex);
        }
        throw new AsmManagerInternalErrorException("Create devices", "DeviceInventoryDAO", e);
    } finally {
        try {
            if (session != null) {
                session.close();
            }
        } catch (Exception ex) {
            logger.warn("Unable to close session during create device: " + ex);
        }
    }

    return device;

}

From source file:com.dell.asm.asmcore.asmmanager.db.DeviceInventoryDAO.java

License:Open Source License

/**
 * Create Device Inventory.//from  w ww  . j  av  a 2 s.  c o  m
 *
 * @param device
 * @return the entity
 */
public DeviceInventoryEntity createDeviceInventory(DeviceInventoryEntity device)
        throws AsmManagerCheckedException {

    Session session = null;
    Transaction tx = null;

    // Save the device in the db.
    try {
        session = _dao._database.getNewSession();
        tx = session.beginTransaction();

        logger.info("Creating device in inventory: " + device.getRefId());

        device.setCreatedDate(new GregorianCalendar());
        device.setDiscoveredDate(new GregorianCalendar());
        device.setCreatedBy(_dao.extractUserFromRequest());
        device.setState(DeviceState.READY);
        session.save(device);

        // Commit transaction.
        tx.commit();
    } catch (ConstraintViolationException cve) {
        logger.warn("Caught exception during device inventory creation: " + cve);
        try {
            if (tx != null) {
                tx.rollback();
            }
        } catch (Exception ex) {
            logger.warn("Unable to rollback transaction during create device: " + ex);
        }
        if (cve.getConstraintName().contains("refid")) {
            throw new AsmManagerCheckedException(AsmManagerCheckedException.REASON_CODE.DUPLICATE_REFID,
                    AsmManagerMessages.duplicateRefId(cve.getSQLException().getMessage()));
        } else if (cve.getConstraintName().contains("service_tag")) {
            throw new AsmManagerCheckedException(AsmManagerCheckedException.REASON_CODE.DUPLICATE_SERVICETAG,
                    AsmManagerMessages.duplicateServiceTag(cve.getSQLException().getMessage()));
        } else {
            throw new AsmManagerCheckedException(AsmManagerCheckedException.REASON_CODE.DUPLICATE_RECORD,
                    AsmManagerMessages.duplicateRecord(cve.getSQLException().getMessage()));
        }
    } catch (Exception e) {
        logger.warn("Caught exception during device inventory creation: " + e);
        try {
            if (tx != null) {
                tx.rollback();
            }
        } catch (Exception ex) {
            logger.warn("Unable to rollback transaction during create device: " + ex);
        }
        throw new AsmManagerInternalErrorException("Create devices", "DeviceInventoryDAO", e);
    } finally {
        try {
            if (session != null) {
                session.close();
            }
        } catch (Exception ex) {
            logger.warn("Unable to close session during create device: " + ex);
        }
    }

    return device;
}

From source file:com.dell.asm.asmcore.asmmanager.db.DeviceInventoryDAO.java

License:Open Source License

/**
 * Create Devices Inventory.// ww w.  j av  a2  s .com
 *
 * @param devices list of devices to add to inventory
 * @return the entities
 */
public List<DeviceInventoryEntity> createDeviceInventory(List<DeviceInventoryEntity> devices)
        throws AsmManagerCheckedException {

    Session session = null;
    Transaction tx = null;

    // Save the device in the db.
    try {
        session = _dao._database.getNewSession();
        tx = session.beginTransaction();

        for (DeviceInventoryEntity device : devices) {
            device.setCreatedDate(new GregorianCalendar());
            device.setCreatedBy(_dao.extractUserFromRequest());
            device.setDiscoveredDate(new GregorianCalendar());
            if (device.getManagedState() == null)
                device.setManagedState(ManagedState.MANAGED);
            if (device.getState() == null)
                device.setState(DeviceState.READY);
            session.save(device);
        }
        // Commit transaction.
        tx.commit();
    } catch (ConstraintViolationException cve) {
        logger.warn("Caught exception during device inventory creation: " + cve);
        try {
            if (tx != null) {
                tx.rollback();
            }
        } catch (Exception ex) {
            logger.warn("Unable to rollback transaction during create device: " + ex);
        }
        if (cve.getConstraintName().contains("refid")) {
            throw new AsmManagerCheckedException(AsmManagerCheckedException.REASON_CODE.DUPLICATE_REFID,
                    AsmManagerMessages.duplicateRefId(cve.getSQLException().getMessage()));
        } else if (cve.getConstraintName().contains("service_tag")) {
            throw new AsmManagerCheckedException(AsmManagerCheckedException.REASON_CODE.DUPLICATE_SERVICETAG,
                    AsmManagerMessages.duplicateServiceTag(cve.getSQLException().getMessage()));
        } else {
            throw new AsmManagerCheckedException(AsmManagerCheckedException.REASON_CODE.DUPLICATE_RECORD,
                    AsmManagerMessages.duplicateRecord(cve.getSQLException().getMessage()));
        }
    } catch (Exception e) {
        logger.warn("Caught exception during device inventory creation: " + e);
        try {
            if (tx != null) {
                tx.rollback();
            }
        } catch (Exception ex) {
            logger.warn("Unable to rollback transaction during create device: " + ex);
        }
        throw new AsmManagerInternalErrorException("Add device", "DeviceInventoryDAO", e);
    } finally {
        try {
            if (session != null) {
                session.close();
            }
        } catch (Exception ex) {
            logger.warn("Unable to close session during create device: " + ex);
        }
    }

    return devices;
}