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:love.sola.netsupport.api.user.ProfileModify.java

License:Open Source License

@Override
protected Object process(HttpServletRequest req, WxSession session) throws Exception {
    User u = session.getAttribute(Attribute.USER);
    ISP isp = checkISP(req.getParameter("isp"));
    String netAccount = checkNetAccount(req.getParameter("username"), isp);
    int block = checkBlock(req.getParameter("block"));
    int room = checkRoom(req.getParameter("room"), block);
    long phone = checkPhoneNumber(req.getParameter("phone"));
    if (room == -1)
        return Error.INVALID_PARAMETER.withMsg("Invalid_Room");
    if (phone == -1)
        return Error.INVALID_PARAMETER.withMsg("Invalid_Phone_Number");
    if (netAccount == null)
        return Error.INVALID_PARAMETER.withMsg("Invalid_Account");

    u.setIsp(isp);/*from   w ww  .  ja  va  2  s . c om*/
    u.setNetAccount(netAccount);
    u.setBlock(block);
    u.setRoom(room);
    u.setPhone(phone);
    try {
        TableUser.update(u);
    } catch (ConstraintViolationException e) {
        String dupKey = e.getConstraintName();
        return Error.INVALID_PARAMETER.withMsg("Duplicated_" + dupKey.toUpperCase());
    }
    session.invalidate();
    return Error.OK;
}

From source file:love.sola.netsupport.api.user.Register.java

License:Open Source License

private Object register(long sid, String name, ISP isp, String netAccount, int block, int room, long phone,
        String wechat) {//from   w  w w  .j  ava  2s .c o  m
    if (sid == -1)
        return Error.INVALID_PARAMETER.withMsg("Invalid_Student_Id");
    if (name == null)
        return Error.INVALID_PARAMETER.withMsg("Invalid_Name");
    if (isp == null)
        return Error.INVALID_PARAMETER.withMsg("Invalid_ISP");
    if (netAccount == null)
        return Error.INVALID_PARAMETER.withMsg("Invalid_Account");
    if (block == -1)
        return Error.INVALID_PARAMETER.withMsg("Invalid_Block");
    if (room == -1)
        return Error.INVALID_PARAMETER.withMsg("Invalid_Room");
    if (phone == -1)
        return Error.INVALID_PARAMETER.withMsg("Invalid_Phone_Number");
    User user = TableUser.getById(sid);
    if (user == null)
        return Error.INVALID_PARAMETER.withMsg("Invalid_Student_Id");
    if (!user.getName().equals(name))
        return Error.INVALID_PARAMETER.withMsg("Invalid_Name");
    if (user.getWechatId() != null)
        return Error.INVALID_PARAMETER.withMsg("User_Already_Registered");
    user.setIsp(isp);
    user.setNetAccount(netAccount);
    user.setBlock(block);
    user.setRoom(room);
    user.setPhone(phone);
    user.setWechatId(wechat);
    try {
        TableUser.update(user);
    } catch (ConstraintViolationException e) {
        String dupKey = e.getConstraintName();
        return Error.INVALID_PARAMETER.withMsg("Duplicated_" + dupKey.toUpperCase()); // PHONE ACCOUNT WECHAT
    }
    return Error.OK;
}

From source file:lucee.runtime.orm.hibernate.CommonUtil.java

License:Open Source License

public static PageException toPageException(Throwable t) {
    PageException pe = caster().toPageException(t);
    ;/*  ww w  . j av a2s  .  c  om*/
    if (t instanceof org.hibernate.HibernateException) {
        org.hibernate.HibernateException he = (org.hibernate.HibernateException) t;
        Throwable cause = he.getCause();
        if (cause != null) {
            pe = caster().toPageException(cause);
            ExceptionUtil.setAdditional(pe, CommonUtil.createKey("hibernate exception"), t);
        }
    }
    if (t instanceof JDBCException) {
        JDBCException je = (JDBCException) t;
        ExceptionUtil.setAdditional(pe, CommonUtil.createKey("sql"), je.getSQL());
    }
    if (t instanceof ConstraintViolationException) {
        ConstraintViolationException cve = (ConstraintViolationException) t;
        if (!Util.isEmpty(cve.getConstraintName())) {
            ExceptionUtil.setAdditional(pe, CommonUtil.createKey("constraint name"), cve.getConstraintName());
        }
    }
    return pe;

}

From source file:ome.services.blitz.impl.DeleteHandleI.java

License:Open Source License

public void steps(SqlAction sql, Session session, Report report) throws Cancel {
    try {// ww  w  . ja  v  a  2 s  .  c  o m

        // Initialize. Any exceptions should cancel the process
        StopWatch sw = new CommonsLogStopWatch();
        DeleteStepFactory factory = new DeleteStepFactory(executor.getContext());
        report.state = new GraphState(factory, sql, session, report.spec);
        report.scheduledDeletes = report.state.getTotalFoundCount();
        if (report.scheduledDeletes == 0L) {
            report.warning = "Object missing.";
            return;
        }
        if (report.scheduledDeletes < Integer.MAX_VALUE) {
            report.stepStarts = new long[(int) report.scheduledDeletes];
            report.stepStops = new long[(int) report.scheduledDeletes];
        }
        sw.stop("omero.delete.ids." + report.scheduledDeletes);

        // Loop throw all steps
        report.warning = "";
        for (int j = 0; j < report.scheduledDeletes; j++) {
            sw = new CommonsLogStopWatch();
            try {
                if (!state.compareAndSet(State.READY, State.RUNNING)) {
                    throw new Cancel("Not ready");
                }
                report.warning += report.state.execute(j);
            } finally {
                sw.stop("omero.delete.step." + j);
                if (report.scheduledDeletes < Integer.MAX_VALUE) {
                    report.stepStarts[j] = sw.getStartTime();
                    report.stepStops[j] = sw.getStartTime() + sw.getElapsedTime();
                }
                // If cancel was thrown, then this value will be overwritten
                // by the try/catch handler
                state.compareAndSet(State.RUNNING, State.READY);
            }
        }
        // If we reach this far, then the delete was successful, so save
        // the deleted id count.
        report.actualDeletes = report.state.getTotalProcessedCount();
    } catch (GraphException de) {
        report.error = de.message;
        Cancel cancel = new Cancel("Cancelled by DeleteException");
        cancel.initCause(de);
        throw cancel;
    } catch (ConstraintViolationException cve) {
        report.error = "ConstraintViolation: " + cve.getConstraintName();
        Cancel cancel = new Cancel("Cancelled by " + report.error);
        cancel.initCause(cve);
        throw cancel;
    } catch (Throwable t) {
        String msg = "Failure during DeleteHandle.steps :";
        report.error = (msg + t);
        log.error(msg, t);
        Cancel cancel = new Cancel("Cancelled by " + t.getClass().getName());
        cancel.initCause(t);
        throw cancel;
    }

}

From source file:ome.services.delete.Deletion.java

License:Open Source License

public void execute(int step) throws Throwable {
    final StopWatch sw = new Slf4JStopWatch();
    try {/*from   w w w.j  a  v a  2 s.  c  o m*/
        warning.append(state.execute(step));
        // TODO: missing stepStart/stepStart calculation here.
        // This hierarchy is duplicated in DeleteI
    } catch (GraphException de) {
        error.append(de.message);
        throw de;
    } catch (ConstraintViolationException cve) {
        error.append("ConstraintViolation: " + cve.getConstraintName());
        throw cve;
    } catch (Throwable t) {
        String msg = "Failure during DeleteHandle.steps :";
        error.append(msg + t);
        log.error(msg, t);
        throw t;
    } finally {
        sw.stop("omero.delete.step." + step);
    }

}

From source file:ome.services.graphs.GraphState.java

License:Open Source License

/**
 * @param validate/*  w  ww.ja  v a2 s  . c  o m*/
 *       after the proper execution of all steps has taken place,
 *       a validation call is made.
 */
public String perform(int j, boolean validate) throws GraphException {

    final GraphStep step = steps.get(j);

    if (validate) {
        if (steps.alreadyValidated(step)) {
            return "";
        }
    } else {
        if (steps.alreadySucceeded(step)) {
            return "";
        }
    }

    String msgOrNull = step.start(this);
    if (msgOrNull != null) {
        return msgOrNull; // EARLY EXIT
    }

    // Add this instance to the opts. Any method which then tries to
    // ask the opts for the current state will have an accurate view.
    step.push(opts);

    try {

        // Lazy initialization of parents.
        // To guarantee that finalization
        // happens (#3125, #3130), a special
        // marker is added and handled above.
        for (GraphStep parent : step.stack) {
            if (!parent.hasSavepoint()) {
                parent.savepoint(this);
            }
        }
        step.savepoint(this);

        try {

            if (!validate) {
                step.action(this, session, sql, opts);
            } else {
                step.validate(this, session, sql, opts);
            }

            // Finalize.
            step.release(this);
            steps.succeeded(step);
            return "";

        } catch (ConstraintViolationException cve) {
            String cause = "ConstraintViolation: " + cve.getConstraintName();
            return handleException(step, cve, cause);
        } catch (GraphException ge) {
            String cause = "GraphException: " + ge.message;
            return handleException(step, ge, cause);
        }

    } finally {
        step.pop(opts);
    }
}

From source file:omero.cmd.graphs.DeleteI.java

License:Open Source License

public Object step(int i) throws Cancel {
    helper.assertStep(i);/*from w w  w.j  a v a2 s.  c  om*/

    try {
        delegate.execute(i);
        return null;
        // This hierarchy is duplicated in Deletion
    } catch (GraphException ge) {
        throw helper.graphException(ge, i, id);
    } catch (ConstraintViolationException cve) {
        throw helper.cancel(err(), cve, "constraint-violation", "name", cve.getConstraintName());
    } catch (Throwable t) {
        throw helper.cancel(err(), t, "failure");
    }
}

From source file:org.etudes.component.app.melete.SectionDB.java

License:Apache License

/**
 * Add section sets the not-null values not been populated yet and then
 * inserts the section into section table.
 * update module witht his association to new added section
 * If error in committing transaction, it rollbacks the transaction.
 *//*from   w  w w .  ja v a2 s  . co  m*/
public Integer addSection(Module module, Section section, boolean fromImport) throws MeleteException {
    try {
        Session session = hibernateUtil.currentSession();
        if (session != null)
            session.clear();
        Transaction tx = null;
        try {
            // set default values for not-null fields
            section.setCreationDate(new java.util.Date());
            section.setModificationDate(new java.util.Date());
            section.setModuleId(module.getModuleId().intValue());
            section.setDeleteFlag(false);

            /*
            * Since Oracle silently transforms "" to nulls, we need to check to see if
            * these non null properties are in fact null.
            */

            hibernateUtil.ensureSectionHasNonNull(section);
            // save object
            if (!session.isOpen()) {
                session = hibernateUtil.currentSession();
            }
            tx = session.beginTransaction();
            session.save(section);

            if (!fromImport) {
                Query query = session.createQuery("from Module mod where mod.moduleId=:moduleId");
                query.setParameter("moduleId", module.getModuleId());
                List secModules = query.list();
                if (secModules != null) {
                    Module secModule = (Module) secModules.get(0);
                    // set xml structure for sequencing and placement of sections
                    String sectionsSeqXML = secModule.getSeqXml();
                    SubSectionUtilImpl SectionUtil = new SubSectionUtilImpl();
                    logger.debug("adding section id to the xmllist" + section.getSectionId().toString());
                    SectionUtil.addSectiontoList(sectionsSeqXML, section.getSectionId().toString());
                    sectionsSeqXML = SectionUtil.storeSubSections();
                    secModule.setSeqXml(sectionsSeqXML);
                    session.saveOrUpdate(secModule);
                } else
                    throw new MeleteException("add_section_fail");
            }

            tx.commit();

            if (logger.isDebugEnabled())
                logger.debug("commiting transaction and new added section id:" + section.getSectionId() + ","
                        + section.getTitle());
            return section.getSectionId();
        } catch (StaleObjectStateException sose) {
            logger.error("add section stale object exception" + sose.toString());
            if (tx != null)
                tx.rollback();
            throw sose;
        } catch (ConstraintViolationException cve) {
            logger.error("constraint voilation exception" + cve.getConstraintName());
            throw cve;
        } catch (HibernateException he) {
            if (tx != null)
                tx.rollback();
            logger.error("add section HE exception" + he.toString());
            throw he;
        } finally {
            hibernateUtil.closeSession();
        }
    } catch (Exception ex) {
        // Throw application specific error
        ex.printStackTrace();
        throw new MeleteException("add_section_fail");
    }

}

From source file:org.etudes.component.app.melete.SectionDB.java

License:Apache License

public Integer editSection(Section section) throws Exception {
    try {/*from  w  ww .j  a  v  a2 s.co  m*/
        Session session = hibernateUtil.currentSession();
        Transaction tx = null;
        try {
            // refresh section object
            Section findSection = getSection(section.getSectionId().intValue());
            findSection.setAudioContent(section.isAudioContent());
            findSection.setContentType(section.getContentType());
            findSection.setInstr(section.getInstr());
            findSection.setModifiedByFname(section.getModifiedByFname());
            findSection.setModifiedByLname(section.getModifiedByLname());
            findSection.setOpenWindow(section.isOpenWindow());
            findSection.setTextualContent(section.isTextualContent());
            findSection.setTitle(section.getTitle());
            findSection.setVideoContent(section.isVideoContent());
            findSection.setModificationDate(new java.util.Date());

            hibernateUtil.ensureSectionHasNonNull(findSection);

            // save object
            if (!session.isOpen())
                session = hibernateUtil.currentSession();
            tx = session.beginTransaction();
            session.saveOrUpdate(findSection);
            session.flush();
            tx.commit();

            if (logger.isDebugEnabled())
                logger.debug("commiting transaction and new added section id:" + section.getSectionId() + ","
                        + section.getTitle());
            return section.getSectionId();

        } catch (StaleObjectStateException sose) {
            if (tx != null)
                tx.rollback();
            logger.error("edit section stale object exception" + sose.toString());
            throw new MeleteException("edit_section_multiple_users");
        } catch (ConstraintViolationException cve) {
            if (tx != null)
                tx.rollback();
            logger.error("constraint voilation exception" + cve.getConstraintName());
            throw new MeleteException("add_section_fail");
        } catch (HibernateException he) {
            if (tx != null)
                tx.rollback();
            logger.error("edit section stale object exception" + he.toString());
            throw new MeleteException("add_section_fail");
        } finally {
            hibernateUtil.closeSession();
        }
    } catch (Exception ex) {
        // Throw application specific error
        throw ex;
    }

}

From source file:org.etudes.component.app.melete.SectionDB.java

License:Apache License

public void editSection(Section section, MeleteResource melResource) throws Exception {
    try {/*from w  ww  .  j ava2 s .  co m*/
        SectionResource secResource = getSectionResourcebyId(section.getSectionId().toString());
        Session session = hibernateUtil.currentSession();
        Transaction tx = null;
        try {
            hibernateUtil.ensureSectionHasNonNull(section);

            // set default values for not-null fields
            //      SectionResource secResource = (SectionResource)section.getSectionResource();
            if (secResource == null)
                secResource = new SectionResource();

            secResource.setSection(section);
            secResource.setResource(melResource);

            section.setModificationDate(new java.util.Date());
            section.setSectionResource(secResource);

            // save object
            if (!session.isOpen())
                session = hibernateUtil.currentSession();
            session.evict(section);
            tx = session.beginTransaction();
            if (melResource != null) {
                String queryString = "from MeleteResource meleteresource where meleteresource.resourceId=:resourceId";
                Query query = session.createQuery(queryString);
                query.setParameter("resourceId", melResource.getResourceId());
                List result_list = query.list();
                if (result_list != null && result_list.size() != 0) {
                    MeleteResource newMelResource = (MeleteResource) result_list.get(0);
                    newMelResource.setLicenseCode(melResource.getLicenseCode());
                    newMelResource.setCcLicenseUrl(melResource.getCcLicenseUrl());
                    newMelResource.setReqAttr(melResource.isReqAttr());
                    newMelResource.setAllowCmrcl(melResource.isAllowCmrcl());
                    newMelResource.setAllowMod(melResource.getAllowMod());
                    newMelResource.setCopyrightYear(melResource.getCopyrightYear());
                    newMelResource.setCopyrightOwner(melResource.getCopyrightOwner());
                    session.saveOrUpdate(newMelResource);
                }
            }
            session.saveOrUpdate(secResource);
            session.saveOrUpdate(section);
            session.flush();
            tx.commit();

            if (logger.isDebugEnabled())
                logger.debug("commit transaction and edit section :" + section.getModuleId() + ","
                        + section.getTitle());
            //        updateExisitingResource(secResource);
            return;

        } catch (StaleObjectStateException sose) {
            if (tx != null)
                tx.rollback();
            logger.error("edit section stale object exception" + sose.toString());
            throw new MeleteException("edit_section_multiple_users");
        } catch (ConstraintViolationException cve) {
            if (tx != null)
                tx.rollback();
            logger.error("constraint voilation exception" + cve.getConstraintName());
            throw new MeleteException("add_section_fail");
        } catch (HibernateException he) {
            if (tx != null)
                tx.rollback();
            logger.error("edit section HE exception" + he.toString());
            he.printStackTrace();
            throw new MeleteException("add_section_fail");
        } finally {
            hibernateUtil.closeSession();
        }
    } catch (Exception ex) {
        // Throw application specific error
        throw ex;
    }
}