List of usage examples for org.hibernate.exception ConstraintViolationException getConstraintName
public String getConstraintName()
From source file:org.jasig.ssp.service.impl.PersonServiceImpl.java
License:Apache License
private Person createUserAccount(String username, Collection<GrantedAuthority> authorities, PersonAttributesLookup personAttributesLookup) { Person person = null;//from w w w . j av a 2 s .c o m if (hasAccountCreationPermission(authorities)) { person = new Person(); person.setEnabled(true); person.setUsername(username); try { // Get the Person Attributes to create the person final PersonAttributesResult attr = personAttributesLookup.lookupPersonAttributes(username); person.setSchoolId(attr.getSchoolId()); person.setFirstName(attr.getFirstName()); person.setLastName(attr.getLastName()); person.setPrimaryEmailAddress(attr.getPrimaryEmailAddress()); ensureRequiredFieldsForDirectoryPerson(person); person = create(person); externalPersonService.updatePersonFromExternalPerson(person); LOGGER.info("Successfully Created Account for {}", username); } catch (final ObjectNotFoundException onfe) { // personAttributesService may throw this exception, if so, // we can't create the user. throw new UnableToCreateAccountException(// NOPMD "Unable to pull required attributes", onfe); } catch (final PersonExistsException pee) { LOGGER.info("Tried to add a user that was already present ({})", username, pee); throw pee; } catch (final ConstraintViolationException sqlException) { // if we received a constraintViolationException of // unique_person_username, then the user might have been // added since we started. (If using SQLServer this will only // work if you're running with ExtendedSQLServer*Dialect. Else // getConstraintName() will always be null.) if (sqlException.getConstraintName().equalsIgnoreCase( "uq_person_school_id")) { LOGGER.info("Tried to add a user that was already present"); throw new ObjectExistsException( "Account with school_id " + person.getSchoolId() + " already exists."); } if (sqlException.getConstraintName().equalsIgnoreCase("unique_person_username")) { LOGGER.info("Tried to add a user that was already present ({})", username, sqlException); // SSP-397. Have to throw something to rollback the // transaction, else Spring/Hib will attempt a commit when // this method returns, which Postgres will refuse with a // "current transaction is aborted" message and the caller // will get an opaque HibernateJdbcException. With an // PersonExistsException the client has at least some // clue as to a reasonable recovery path. throw new PersonExistsException("Account with user name " + username + " already exists."); } // Also SSP-397 throw sqlException; } catch (final Exception genException) { // This exception seems to get swallowed... trying to reveal // it. throw new UnableToCreateAccountException( // NOPMD "Unable to Create Account for login.", genException); } } else { throw new UnableToCreateAccountException( // NOPMD // already know the account was not found "Insufficient Permissions to create Account"); } return person; }
From source file:org.jasig.ssp.service.impl.WatchStudentServiceImpl.java
License:Apache License
@Override public WatchStudent create(final WatchStudent obj) throws ObjectNotFoundException, ValidationException, ObjectExistsException { try {//from w ww.jav a 2 s .c o m return super.create(obj); } catch (final ConstraintViolationException e) { if (e.getConstraintName().equalsIgnoreCase("watch_student_watcher_id_student_id_key")) { final LinkedHashMap<String, UUID> lookupKeys = Maps.newLinkedHashMap(); lookupKeys.put("watcherId", obj.getPerson().getId()); lookupKeys.put("studentId", obj.getStudent().getId()); throw new ObjectExistsException(WatchStudent.class.getName(), lookupKeys, e); } throw new ObjectExistsException("Constraint violation trying to store a WatchStudent record", e); } }
From source file:org.jspresso.framework.application.frontend.controller.AbstractFrontendController.java
License:Open Source License
/** * Refines the data integrity violation exception to determine the translation * key from which the user message will be constructed. * * @param exception// w w w . java 2 s.c o m * the DataIntegrityViolationException. * @return the translation key to use. */ protected String refineIntegrityViolationTranslationKey(DataIntegrityViolationException exception) { if (exception.getCause() instanceof ConstraintViolationException) { ConstraintViolationException cve = (ConstraintViolationException) exception.getCause(); if (cve.getSQL() != null && cve.getSQL().toUpperCase().contains("DELETE")) { return "error.fk.delete"; } if (cve.getConstraintName() != null) { if (cve.getConstraintName().toUpperCase().contains("FK")) { return "error.fk.update"; } return "error.unicity"; } return "error.integrity"; } return "error.integrity"; }
From source file:org.jspresso.framework.application.frontend.controller.AbstractFrontendController.java
License:Open Source License
/** * Computes a user friendly exception message if this exception is known and * can be cleanly handled by the framework. * * @param exception//from ww w . j ava 2 s . c o m * the exception to compute the message for. * @return the user friendly message or null if this exception is unexpected. */ protected String computeUserFriendlyExceptionMessage(Throwable exception) { if (exception instanceof SecurityException) { return exception.getMessage(); } if (exception instanceof BusinessException) { return ((BusinessException) exception).getI18nMessage(this, getLocale()); } if (exception instanceof DataIntegrityViolationException) { String constraintTranslation = null; if (exception.getCause() instanceof ConstraintViolationException) { ConstraintViolationException cve = ((ConstraintViolationException) exception.getCause()); if (cve.getConstraintName() != null) { constraintTranslation = getTranslation(cve.getConstraintName(), getLocale()); } } if (constraintTranslation == null) { constraintTranslation = getTranslation("unknown", getLocale()); } return getTranslation( refineIntegrityViolationTranslationKey((DataIntegrityViolationException) exception), new Object[] { constraintTranslation }, getLocale()); } if (exception instanceof ConcurrencyFailureException) { return getTranslation("concurrency.error.description", getLocale()); } return null; }
From source file:org.n52.sos.ds.hibernate.InsertObservationDAO.java
License:Open Source License
@Override public synchronized InsertObservationResponse insertObservation(final InsertObservationRequest request) throws OwsExceptionReport { final InsertObservationResponse response = new InsertObservationResponse(); response.setService(request.getService()); response.setVersion(request.getVersion()); Session session = null;/* www . ja v a2 s .c o m*/ Transaction transaction = null; // TODO: check unit and set if available and not defined in DB try { session = sessionHolder.getSession(); transaction = session.beginTransaction(); final CompositeOwsException exceptions = new CompositeOwsException(); final Set<String> allOfferings = Sets.newHashSet(); allOfferings.addAll(request.getOfferings()); // cache/tracking objects to avoid redundant queries Map<AbstractFeature, FeatureOfInterest> featureCache = Maps.newHashMap(); Table<OmObservationConstellation, String, ObservationConstellation> obsConstOfferingHibernateObsConstTable = HashBasedTable .create(); Map<String, Codespace> codespaceCache = Maps.newHashMap(); Map<String, Unit> unitCache = Maps.newHashMap(); HashMultimap<OmObservationConstellation, String> obsConstOfferingCheckedMap = HashMultimap.create(); HashMultimap<AbstractFeature, String> relatedFeatureCheckedMap = HashMultimap.create(); // counter for batch flushing int obsCount = 0; for (final OmObservation sosObservation : request.getObservations()) { // check strict spatial filtering profile if (ServiceConfiguration.getInstance().isStrictSpatialFilteringProfile() && !sosObservation.isSetSpatialFilteringProfileParameter()) { throw new MissingParameterValueException(Sos2Constants.InsertObservationParams.parameter) .withMessage("The sampling geometry definition is missing in the observation because" + " the Spatial Filtering Profile is specification conformant. To use a less" + " restrictive Spatial Filtering Profile you can change this in the Service-Settings!"); } final OmObservationConstellation sosObsConst = sosObservation.getObservationConstellation(); Set<String> offerings = getParentProcedureOfferings(sosObsConst); sosObsConst.setOfferings(offerings); allOfferings.addAll(offerings); final Set<ObservationConstellation> hObservationConstellations = new HashSet<ObservationConstellation>( 0); FeatureOfInterest hFeature = null; // TODO cache obsConst and feature (multi obs often have the // same) for (final String offeringID : sosObsConst.getOfferings()) { ObservationConstellation hObservationConstellation = obsConstOfferingHibernateObsConstTable .get(sosObsConst, offeringID); if (hObservationConstellation == null) { if (!obsConstOfferingCheckedMap.containsEntry(sosObsConst, offeringID)) { try { hObservationConstellation = observationConstellationDAO .checkObservationConstellation(sosObsConst, offeringID, session, Sos2Constants.InsertObservationParams.observationType.name()); // add to cache table obsConstOfferingHibernateObsConstTable.put(sosObsConst, offeringID, hObservationConstellation); } catch (final OwsExceptionReport owse) { exceptions.add(owse); } // mark as checked obsConstOfferingCheckedMap.put(sosObsConst, offeringID); } } if (hObservationConstellation != null) { // get feature from local cache or create if necessary hFeature = getFeature(sosObsConst.getFeatureOfInterest(), featureCache, session); // only do feature checking once for each // AbstractFeature/offering combo if (!relatedFeatureCheckedMap.containsEntry(sosObsConst.getFeatureOfInterest(), offeringID)) { featureOfInterestDAO.checkOrInsertFeatureOfInterestRelatedFeatureRelation(hFeature, hObservationConstellation.getOffering(), session); relatedFeatureCheckedMap.put(sosObsConst.getFeatureOfInterest(), offeringID); } hObservationConstellations.add(hObservationConstellation); } } if (!hObservationConstellations.isEmpty()) { final AbstractObservationDAO observationDAO = DaoFactory.getInstance().getObservationDAO(); if (sosObservation.getValue() instanceof SingleObservationValue) { observationDAO.insertObservationSingleValue(hObservationConstellations, hFeature, sosObservation, codespaceCache, unitCache, session); } else if (sosObservation.getValue() instanceof MultiObservationValues) { observationDAO.insertObservationMultiValue(hObservationConstellations, hFeature, sosObservation, codespaceCache, unitCache, session); } } // flush every FLUSH_INTERVAL if (++obsCount % FLUSH_THRESHOLD == 0) { session.flush(); session.clear(); } } request.setOfferings(Lists.newArrayList(allOfferings)); // if no observationConstellation is valid, throw exception if (exceptions.size() == request.getObservations().size()) { throw exceptions; } session.flush(); transaction.commit(); } catch (final HibernateException he) { if (transaction != null) { transaction.rollback(); } HTTPStatus status = HTTPStatus.INTERNAL_SERVER_ERROR; String exceptionMsg = "Error while inserting new observation!"; if (he instanceof JDBCException) { if (he instanceof ConstraintViolationException) { final ConstraintViolationException cve = (ConstraintViolationException) he; checkEqualsAndThrow(cve.getConstraintName(), he); checkContainsAndThrow(cve.getMessage(), he); } SQLException sqle = ((JDBCException) he).getSQLException(); checkContainsAndThrow(sqle.getMessage(), he); // if this is a JDBCException, pass the underlying SQLException // as the causedBy exception so that we can show the actual error in the // OwsExceptionReport when batching CompositeOwsException e = new CompositeOwsException(); for (Throwable next : sqle) { checkContainsAndThrow(next.getMessage(), he); e.add(new NoApplicableCodeException().causedBy(next)); } throw e.setStatus(status); } else { throw new NoApplicableCodeException().causedBy(he).withMessage(exceptionMsg).setStatus(status); } } finally { sessionHolder.returnSession(session); } /* * TODO: ... all the DS insertion stuff Requirement 68 * proc/obsProp/Offering same obsType; */ return response; }
From source file:org.openbravo.advpaymentmngt.actionHandler.ModifyPaymentPlanActionHandler.java
License:Open Source License
@Override /**/*from ww w . ja v a2s. c o m*/ * Receives the modified payment plan for a given invoice */ protected JSONObject doExecute(Map<String, Object> parameters, String content) { JSONObject jsonRequest = null; try { jsonRequest = new JSONObject(content); String strInvoiceId = jsonRequest.getString("inpcInvoiceId"); if (strInvoiceId == null || strInvoiceId.isEmpty() || "null".equalsIgnoreCase(strInvoiceId)) { strInvoiceId = jsonRequest.getString("C_Invoice_ID"); } Invoice invoice = OBDal.getInstance().get(Invoice.class, strInvoiceId); JSONArray gridRows = jsonRequest.getJSONArray(ApplicationConstants.ALL_ROWS_PARAM); List<FIN_PaymentSchedule> databaseRows = new ArrayList<FIN_PaymentSchedule>(); databaseRows = getDatabaseRows(invoice); // TODO:Review if we should allow this option // if (paidAnyAmount(invoice)) { // return addMessage(jsonRequest, "@APRM_AlreadyPaidInvoice@", "error"); // } String errorMsg = validateGridAmounts(gridRows, invoice); if (errorMsg != null) { OBDal.getInstance().rollbackAndClose(); return addMessage(jsonRequest, errorMsg, "error"); } if (!validateInvoiceAmounts(invoice)) { OBDal.getInstance().rollbackAndClose(); return addMessage(jsonRequest, "@APRM_ExistingPlanIsNotCorrect@", "error"); } List<JSONObject> lToCreate = getNewRows(gridRows); List<FIN_PaymentSchedule> lToRemove = getRemovedRows(databaseRows, gridRows); List<FIN_PaymentSchedule> lToModify = getModifiedRows(databaseRows, gridRows, lToCreate, lToRemove); HashMap<FIN_PaymentSchedule, BigDecimal> orders = getOrders(lToRemove, lToModify); HashMap<FIN_PaymentDetail, BigDecimal> canceledPSDs = getCanceledPSDs(lToRemove, lToModify); removeRows(lToRemove, invoice); List<FIN_PaymentSchedule> createdPSs = createRows(lToCreate, invoice); createdPSs = modifyRows(lToModify, gridRows, invoice, createdPSs); createPSDetails(createdPSs, orders); assignCanceled(invoice, canceledPSDs); if (!ordersSumsZero(orders, invoice.getFINPaymentScheduleList().get(0))) { OBDal.getInstance().rollbackAndClose(); return addMessage(jsonRequest, "@APRM_AmountNotFullyAllocated@", "error"); } if (!validateInvoiceAmounts(invoice)) { OBDal.getInstance().rollbackAndClose(); return addMessage(jsonRequest, "@APRM_AmountMismatch@", "error"); } // As a final step, Payment Monitor information for this invoice is updated. FIN_PaymentMonitorProcess.updateInvoice(invoice); return addMessage(jsonRequest, "@Success@", "success"); } catch (ConstraintViolationException e) { OBDal.getInstance().rollbackAndClose(); log4j.error("Exception! " + e); String constraint = e.getConstraintName(); constraint = constraint.substring(constraint.lastIndexOf(".") + 1, constraint.length()); try { return addMessage(jsonRequest, "@" + constraint + "@", "error"); } catch (Exception ex) { log4j.error("Exception! " + ex); return jsonRequest; } } catch (Exception e) { OBDal.getInstance().rollbackAndClose(); log4j.error("Exception! " + e); try { return addMessage(jsonRequest, "@ProcessRunError@", "error"); } catch (Exception ex) { log4j.error("Exception! " + ex); return jsonRequest; } } }
From source file:org.openeos.services.ui.internal.PostgreSQLDialectBatchUpdateResolver.java
License:Apache License
@Override protected Throwable unencapsuleThrowable(Throwable t) { if (t instanceof ConstraintViolationException) { ConstraintViolationException constrainEx = (ConstraintViolationException) t; if (constrainEx.getConstraintName() == null) { SQLException sqlEx = constrainEx.getSQLException(); if (sqlEx instanceof BatchUpdateException) { SQLException other = sqlEx.getNextException(); if (other != null) { String constraintName = conversionContext.getViolatedConstraintNameExtracter() .extractConstraintName(other); if (constraintName != null) { return new ConstraintViolationException(t.getMessage(), sqlEx, constraintName); }//from w w w.j a va 2 s . c o m } } } } return null; }
From source file:org.openlmis.fulfillment.web.errorhandler.ServiceErrorHandling.java
License:Open Source License
/** * Handles data integrity violation exception. * * @param ex the data integrity exception * @return the user-oriented error message. *///from w ww .j a v a 2 s.c o m @ExceptionHandler(DataIntegrityViolationException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) public ResponseEntity<Message.LocalizedMessage> handleDataIntegrityViolation( DataIntegrityViolationException ex) { if (ex.getCause() instanceof ConstraintViolationException) { ConstraintViolationException cause = (ConstraintViolationException) ex.getCause(); String messageKey = CONSTRAINT_MAP.get(cause.getConstraintName()); if (messageKey != null) { logger.error(CONSTRAINT_VIOLATION, ex); return new ResponseEntity<>(getLocalizedMessage(new Message(messageKey)), HttpStatus.BAD_REQUEST); } else { return new ResponseEntity<>( logErrorAndRespond(CONSTRAINT_VIOLATION, MessageKeys.CONSTRAINT_VIOLATION, ex.getMessage()), HttpStatus.BAD_REQUEST); } } return new ResponseEntity<>( logErrorAndRespond("Data integrity violation", DATA_INTEGRITY_VIOLATION, ex.getMessage()), CONFLICT); }
From source file:org.openlmis.referencedata.errorhandling.RefDataErrorHandling.java
License:Open Source License
/** * Handles data integrity violation exception. * @param dive the data integrity exception * @return the user-oriented error message. *///from ww w. j a v a 2s . co m @ExceptionHandler(DataIntegrityViolationException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) @ResponseBody public LocalizedMessage handleDataIntegrityViolation(DataIntegrityViolationException dive) { LOGGER.info(dive.getMessage()); if (dive.getCause() instanceof ConstraintViolationException) { ConstraintViolationException cause = (ConstraintViolationException) dive.getCause(); String messageKey = CONSTRAINT_MAP.get(cause.getConstraintName()); if (messageKey != null) { return getLocalizedMessage(new Message(messageKey)); } } return getLocalizedMessage(dive.getMessage()); }
From source file:org.vectorcorp.security.beans.RegisterBean.java
public String registerAccount() { String viewName;//from w w w. j ava2s. c o m AccessControl ac = new AccessControl(); errorMsg = ""; ac.setUserName(userName); ac.setPassword(new byte[] { 0x01 }); ac.setStatus(AccessKeeper.STATUS_EXPIRED); ac.setValidTill(Calendar.getInstance().getTime()); try { AccessKeeper.createAccessControl(ac, selectedRoles); viewName = SUCCESS_PAGE; } catch (ConstraintViolationException cve) { if (AccessControl.PK_NAME.equals(cve.getConstraintName())) errorMsg = DUPLICATE_NAME; viewName = FAILURE_PAGE; } catch (JDBCException e) { errorMsg = e.getSQLException().getMessage(); viewName = FAILURE_PAGE; } return viewName; }