Example usage for org.hibernate.exception ConstraintViolationException getConstraintName

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

Introduction

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

Prototype

public String getConstraintName() 

Source Link

Document

Returns the name of the violated constraint, if known.

Usage

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

License:Open Source License

/**
 * Create Devices Inventory./* w  w w  .  j  a  v  a 2 s.  co  m*/
 *
 * @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;
}

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

License:Open Source License

/**
 * Create Discovery Result.//from  w  w w .  j  a v a 2s .  c o  m
 * @param result
 * @return the entity
 */
public DiscoveryResultEntity createDiscoveryResult(DiscoveryResultEntity result)
        throws AsmManagerCheckedException {

    Session session = null;
    Transaction tx = null;

    // Save the device in the db.
    try {
        session = _dao._database.getNewSession();
        tx = session.beginTransaction();
        session.save(result);
        result.setCreatedDate(new Date());
        result.setCreatedBy(_dao.extractUserFromRequest());
        // Commit transaction.
        tx.commit();
    } catch (ConstraintViolationException cve) {
        logger.warn("Caught exception during discovery result creation: " + cve);
        try {
            if (tx != null) {
                tx.rollback();
            }
        } catch (Exception ex) {
            logger.warn("Unable to rollback transaction during create discovery result: " + ex);
        }
        if (cve.getConstraintName().contains("refid")) {
            //throw new AsmManagerDAOException(AsmManagerDAOException.REASON_CODE.DUPLICATE_JOBID, cve);
            throw new AsmManagerCheckedException(AsmManagerCheckedException.REASON_CODE.DUPLICATE_JOBID,
                    AsmManagerMessages.duplicateRefId(cve.getSQLException().getMessage()));
        } else {
            //throw new AsmManagerDAOException(AsmManagerDAOException.REASON_CODE.DUPLICATE_RECORD, cve);
            throw new AsmManagerCheckedException(AsmManagerCheckedException.REASON_CODE.DUPLICATE_RECORD,
                    AsmManagerMessages.duplicateRefId(cve.getSQLException().getMessage()));
        }
    } catch (Exception e) {
        logger.warn("Caught exception during discovery result creation: " + e);
        try {
            if (tx != null) {
                tx.rollback();
            }
        } catch (Exception ex) {
            logger.warn("Unable to rollback transaction during create discovery result: " + ex);
        }
        //throw new AsmManagerDAOException("Caught exception during discovery result creation: ", e);
        throw new AsmManagerInternalErrorException("Error Creating Discovery result", "DiscoveryResultDAO", e);
    } finally {
        try {
            if (session != null) {
                session.close();
            }
        } catch (Exception ex) {
            logger.warn("Unable to close session during create device: " + ex);
        }
    }

    return result;
}

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

License:Open Source License

/**
 * create or Update Discovery Result.//w  w  w . j  ava 2 s. c  o m
 * @param newResult the result to update.
 */

public void createOrUpdateDiscoveryResult(DiscoveryResultEntity newResult) throws AsmManagerCheckedException {

    Session session = null;
    Transaction tx = null;
    DiscoveryResultEntity discoveryResultEntity = new DiscoveryResultEntity();
    try {
        session = _dao._database.getNewSession();
        tx = session.beginTransaction();
        String hql = "from DiscoveryResultEntity where refId = :refId";
        Query query = session.createQuery(hql);
        query.setString("refId", newResult.getRefId());
        discoveryResultEntity = (DiscoveryResultEntity) query.setMaxResults(1).uniqueResult();

        if (discoveryResultEntity == null) {
            discoveryResultEntity = new DiscoveryResultEntity();
            discoveryResultEntity.setRefId(newResult.getRefId());
            discoveryResultEntity.setRefType(newResult.getRefType());
            discoveryResultEntity.setParentJobId(newResult.getParentJobId());
            discoveryResultEntity.setJobId(newResult.getJobId());
        }
        discoveryResultEntity.setDeviceRefId(newResult.getDeviceRefId());
        discoveryResultEntity.setDeviceType(newResult.getDeviceType());
        discoveryResultEntity.setStatus(newResult.getStatus());
        discoveryResultEntity.setStatusMessage(newResult.getStatusMessage());
        discoveryResultEntity.setServiceTag(newResult.getServiceTag());
        discoveryResultEntity.setIpaddress(newResult.getIpaddress());
        discoveryResultEntity.setModel(newResult.getModel());
        //logger.info("serer count and iom count: " + newResult.getServerCount() + " : "+newResult.getIomCount());
        discoveryResultEntity.setServerCount(newResult.getServerCount());
        discoveryResultEntity.setIomCount(newResult.getIomCount());
        discoveryResultEntity.setServerType(newResult.getServerType());
        discoveryResultEntity.setHealthState(newResult.getHealthState());
        discoveryResultEntity.setHealthStatusMsg(newResult.getHealthStatusMsg());
        discoveryResultEntity.setVendor(newResult.getVendor());
        discoveryResultEntity.setSystem_id(newResult.getSystem_id());

        discoveryResultEntity.setUpdatedDate(new Date());
        discoveryResultEntity.setUpdatedBy(_dao.extractUserFromRequest());
        discoveryResultEntity.setFacts(newResult.getFacts());
        discoveryResultEntity.setUnmanaged(newResult.isUnmanaged());
        discoveryResultEntity.setReserved(newResult.isReserved());
        discoveryResultEntity.setConfig(newResult.getConfig());
        discoveryResultEntity.setDiscoverDeviceType(newResult.getDiscoverDeviceType());
        discoveryResultEntity.setServerPoolId(newResult.getServerPoolId());

        if (newResult.getFirmwareList() != null)
            for (FirmwareDeviceInventoryEntity fdie : newResult.getFirmwareList()) {
                discoveryResultEntity.addFirmwareDeviceInventoryEntity(fdie);
            }

        session.saveOrUpdate(discoveryResultEntity);

        // Commit transaction.
        tx.commit();
    } catch (ConstraintViolationException cve) {
        logger.warn("Caught exception during discovery result creation: " + cve);
        try {
            if (tx != null) {
                tx.rollback();
            }
        } catch (Exception ex) {
            logger.warn("Unable to rollback transaction during create discovery result: " + ex);
        }
        if (cve.getConstraintName().contains("refid")) {
            //throw new AsmManagerDAOException(AsmManagerDAOException.REASON_CODE.DUPLICATE_JOBID, cve);
            throw new AsmManagerCheckedException(AsmManagerCheckedException.REASON_CODE.DUPLICATE_JOBID,
                    AsmManagerMessages.duplicateRefId(cve.getSQLException().getMessage()));
        } else {
            //throw new AsmManagerDAOException(AsmManagerDAOException.REASON_CODE.DUPLICATE_RECORD, cve);
            throw new AsmManagerCheckedException(AsmManagerCheckedException.REASON_CODE.DUPLICATE_RECORD,
                    AsmManagerMessages.duplicateRefId(cve.getSQLException().getMessage()));
        }
    } catch (Exception e) {
        logger.warn("Caught exception during update device: " + e);
        try {
            if (tx != null) {
                tx.rollback();
            }
        } catch (Exception ex) {
            logger.warn("Unable to rollback transaction during update device: " + ex);
        }
        if (e instanceof AsmManagerCheckedException) {
            throw e;
        }
        throw new AsmManagerInternalErrorException("Error updating the discovery result", "DiscoveryResultDAO",
                e);
    } finally {
        try {
            if (session != null) {
                session.close();
            }
        } catch (Exception ex) {
            logger.warn("Unable to close session during update device: " + ex);
        }
    }
}

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

License:Open Source License

/**
 * Create Device Inventory.//from  w  ww . ja  v a2s . c  o  m
 * @param device
 * @return the entity
 */
public MapRazorNodeNameToSerialNumberEntity createRazorNode(MapRazorNodeNameToSerialNumberEntity 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 MapRazorNodeNameToSerialNumberEntity in inventory: " + device.getId());

        session.save(device);

        // Commit transaction.
        tx.commit();
    } catch (ConstraintViolationException cve) {
        logger.warn("Caught exception during MapRazorNodeNameToSerialNumberEntity 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 MapRazorNodeNameToSerialNumberEntity 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", "MapRazorNodeNameToSerialNumberDAO", 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.ServiceTemplateDAO.java

License:Open Source License

public ServiceTemplateEntity createTemplate(ServiceTemplateEntity template) throws AsmManagerCheckedException {

    Session session = null;/*from  www . ja  va 2  s  . c o  m*/
    Transaction tx = null;
    // Save the template in the db.
    try {
        session = _dao._database.getNewSession();
        tx = session.beginTransaction();

        //TODO remove the set created date when @PrePersist is working
        GregorianCalendar now = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
        template.setCreatedDate(now);
        template.setCreatedBy(_dao.extractUserFromRequest());
        session.save(template);
        // Commit transaction and clean up.
        tx.commit();
    } catch (ConstraintViolationException cve) {
        logger.warn("Caught Exception during Template creation: " + cve);
        try {
            if (tx != null) {
                tx.rollback();
            }
        } catch (Exception ex) {
            logger.warn("unable to rollback during template creation" + ex);
        }
        if (cve.getConstraintName().contains("name")) {
            throw new AsmManagerCheckedException(AsmManagerCheckedException.REASON_CODE.DUPLICATE_RECORD,
                    AsmManagerMessages.duplicateRecord(cve.getSQLException().getMessage()));
        }
    } catch (Exception e) {
        logger.warn("Caught exception during template creation: " + e);
        try {
            if (tx != null)
                tx.rollback();
        } catch (Exception e2) {
            logger.warn("Caught exception during template creation" + e2);
        }
    } finally {
        try {
            if (session != null)
                session.close();
        } catch (Exception e2) {
            logger.warn("Caught exception during template creation" + e2);
        }
    }

    return template;
}

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

License:Open Source License

public TemplateEntity createTemplate(TemplateEntity template) throws AsmManagerCheckedException {

    Session session = null;//from   www.  j  a  v a2 s  .  c om
    Transaction tx = null;
    // Save the template in the db.
    try {
        session = _dao._database.getNewSession();
        tx = session.beginTransaction();

        //TODO remove the set created date when @PrePersist is working
        GregorianCalendar now = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
        template.setCreatedDate(now);
        template.setCreatedBy(_dao.extractUserFromRequest());
        session.save(template);
        // Commit transaction and clean up.
        tx.commit();
    } catch (ConstraintViolationException cve) {
        logger.warn("Caught Exception during Template creation: " + cve);
        try {
            if (tx != null) {
                tx.rollback();
            }
        } catch (Exception ex) {
            logger.warn("unable to rollback during template creation" + ex);
        }
        if (cve.getConstraintName().contains("name")) {
            throw new AsmManagerCheckedException(AsmManagerCheckedException.REASON_CODE.DUPLICATE_RECORD,
                    AsmManagerMessages.duplicateRecord(cve.getSQLException().getMessage()));
        }
    } catch (Exception e) {
        logger.warn("Caught exception during template creation: " + e);
        try {
            if (tx != null)
                tx.rollback();
        } catch (Exception e2) {
            logger.warn("Caught exception during template creation" + e2);
        }
    } finally {
        try {
            if (session != null)
                session.close();
        } catch (Exception e2) {
            logger.warn("Caught exception during template creation" + e2);
        }
    }

    return template;
}

From source file:com.evolveum.midpoint.repo.sql.helpers.ObjectUpdater.java

License:Apache License

public <T extends ObjectType> String addObjectAttempt(PrismObject<T> object, RepoAddOptions options,
        OperationResult result) throws ObjectAlreadyExistsException, SchemaException {

    LOGGER_PERFORMANCE.debug("> add object {}, oid={}, overwrite={}",
            object.getCompileTimeClass().getSimpleName(), object.getOid(), options.isOverwrite());

    String oid = null;/*from w  w w.  ja  v a 2  s .  c o m*/
    Session session = null;
    OrgClosureManager.Context closureContext = null;
    // it is needed to keep the original oid for example for import options. if we do not keep it
    // and it was null it can bring some error because the oid is set when the object contains orgRef
    // or it is org. and by the import we do not know it so it will be trying to delete non-existing object
    String originalOid = object.getOid();
    try {
        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace("Object\n{}", new Object[] { object.debugDump() });
        }

        LOGGER.trace("Translating JAXB to data type.");
        PrismIdentifierGenerator.Operation operation = options.isOverwrite()
                ? PrismIdentifierGenerator.Operation.ADD_WITH_OVERWRITE
                : PrismIdentifierGenerator.Operation.ADD;

        RObject rObject = createDataObjectFromJAXB(object, operation);

        session = baseHelper.beginTransaction();

        closureContext = closureManager.onBeginTransactionAdd(session, object, options.isOverwrite());

        if (options.isOverwrite()) {
            oid = overwriteAddObjectAttempt(object, rObject, originalOid, session, closureContext, result);
        } else {
            oid = nonOverwriteAddObjectAttempt(object, rObject, originalOid, session, closureContext);
        }
        session.getTransaction().commit();

        LOGGER.trace("Saved object '{}' with oid '{}'",
                new Object[] { object.getCompileTimeClass().getSimpleName(), oid });

        object.setOid(oid);
    } catch (ConstraintViolationException ex) {
        handleConstraintViolationException(session, ex, result);
        baseHelper.rollbackTransaction(session, ex, result, true);

        LOGGER.debug("Constraint violation occurred (will be rethrown as ObjectAlreadyExistsException).", ex);
        // we don't know if it's only name uniqueness violation, or something else,
        // therefore we're throwing it always as ObjectAlreadyExistsException revert
        // to the original oid and prevent of unexpected behaviour (e.g. by import with overwrite option)
        if (StringUtils.isEmpty(originalOid)) {
            object.setOid(null);
        }
        String constraintName = ex.getConstraintName();
        // Breaker to avoid long unreadable messages
        if (constraintName != null
                && constraintName.length() > SqlRepositoryServiceImpl.MAX_CONSTRAINT_NAME_LENGTH) {
            constraintName = null;
        }
        throw new ObjectAlreadyExistsException(
                "Conflicting object already exists"
                        + (constraintName == null ? "" : " (violated constraint '" + constraintName + "')"),
                ex);
    } catch (ObjectAlreadyExistsException | SchemaException ex) {
        baseHelper.rollbackTransaction(session, ex, result, true);
        throw ex;
    } catch (DtoTranslationException | RuntimeException ex) {
        baseHelper.handleGeneralException(ex, session, result);
    } finally {
        cleanupClosureAndSessionAndResult(closureContext, session, result);
    }

    return oid;
}

From source file:com.kirana.dao.ProductDaoImpl.java

@Override
public boolean addProductBulk(List<Product> products) throws Exception {
    boolean status = false;
    try {//from   ww w.ja va2s.  c  om
        session = sessionFactory.openSession();
        tx = session.beginTransaction();
        int i = 0;
        for (Product product : products) {
            session.save(product);
            if (i % BATCH_INSERT_SIZE == 0) { // Same as the JDBC batch size
                //flush a batch of inserts and release memory:
                session.flush();
                session.clear();
            }
        }
        tx.commit();
        session.close();
        status = true;
    } catch (ConstraintViolationException ex) {
        throw new ParameterException("DB insert problem,constraint caused the problem :"
                + ex.getConstraintName() + "Message :" + ex.getMessage());
    }

    return status;
}

From source file:de.micromata.genome.jpa.EmgrFactory.java

License:Apache License

/**
 * Convert exception.//www.j a v a  2  s. co m
 *
 * @param ex the ex
 * @return the runtime exception
 */
public static RuntimeException convertException(RuntimeException ex) {
    if (ex instanceof QueryTimeoutException) {
        // this is a oracle/hibernate bug workouround.
        // hibernate think this is is a query timeout, but should a DataException
        if (ex.getCause() instanceof org.hibernate.QueryTimeoutException) {
            org.hibernate.QueryTimeoutException qto = (org.hibernate.QueryTimeoutException) ex.getCause();
            if (qto.getCause() instanceof SQLException) {
                SQLException sqlex = (SQLException) qto.getCause();
                // ORA-12899
                if (sqlex.getErrorCode() == 12899) {
                    return new DataPersistenceException(ex.getMessage(), qto.getSQL(), sqlex.getSQLState(), ex);
                }
            }
        }
    }
    if (ex instanceof PersistenceException) {
        Throwable cause = ex.getCause();
        if (cause instanceof ConstraintViolationException) {
            ConstraintViolationException cve = (ConstraintViolationException) cause;
            cve.getMessage();
            String sql = cve.getSQL();
            return new ConstraintPersistenceException(cve.getMessage(), sql, cve.getSQLState(),
                    cve.getConstraintName(), ex);
        } else if (cause instanceof DataException) {
            DataException dex = (DataException) cause;
            return new DataPersistenceException(ex.getMessage(), dex.getSQL(), dex.getSQLState(), ex);
        } else if (cause instanceof PropertyValueException) {
            if (StringUtils.startsWith(cause.getMessage(), "not-null ") == true) {
                return new NullableConstraintPersistenceException(ex.getMessage(), ex);
            }
        }
    }
    return ex;
}

From source file:jcms.integrationtier.exception.ConstraintViolationExceptionMySqlPatch.java

License:Open Source License

public ConstraintViolationExceptionMySqlPatch(ConstraintViolationException cve) {
    super(cve.getMessage(), cve.getSQLException(), cve.getSQL(), cve.getConstraintName());
    this.constraintName = extractConstraintName();
}