/** * 处理JPA的异常 * * @param ex * @param request * @return */ @ExceptionHandler(value = {JpaSystemException.class}) public ResponseEntity<ErrorResponse> handleJpaException(Exception ex, WebRequest request) { if (log.isDebugEnabled()) { log.debug("handling exception ==> " + request.getDescription(true)); } RestException rex = new RestException(PARAMS_RESOLUTION_ERROR, ex.getLocalizedMessage()); ErrorResponse res = new ErrorResponse(rex); return new ResponseEntity<>(res, rex.getHttpStatus()); }
private VmNicVO persistAndRetryIfMacCollision(VmNicVO vo) { int tries = 5; while (tries-- > 0) { try { vo = dbf.persistAndRefresh(vo); return vo; } catch (JpaSystemException e) { if (e.getRootCause() instanceof MySQLIntegrityConstraintViolationException && e.getRootCause().getMessage().contains("Duplicate entry")) { logger.debug(String.format("Concurrent mac allocation. Mac[%s] has been allocated, try allocating another one. " + "The error[Duplicate entry] printed by jdbc.spi.SqlExceptionHelper is no harm, " + "we will try finding another mac", vo.getMac())); logger.trace("", e); vo.setMac(NetworkUtils.generateMacWithDeviceId((short) vo.getDeviceId())); } else { throw e; } } } return null; }
@Test public void testDuplicateUniqueValuesAreRejectedWithChecking_TestingDisabled() { myDaoConfig.setUniqueIndexesCheckedBeforeSave(false); createUniqueBirthdateAndGenderSps(); Patient pt1 = new Patient(); pt1.setGender(Enumerations.AdministrativeGender.MALE); pt1.setBirthDateElement(new DateType("2011-01-01")); myPatientDao.create(pt1).getId().toUnqualifiedVersionless(); try { myPatientDao.create(pt1).getId().toUnqualifiedVersionless(); fail(); } catch (JpaSystemException e) { // good } }
@RequestMapping(value = "/{configType}_configs/{configName}", method = RequestMethod.DELETE, produces = "text/html") public String delete(@PathVariable String configType, @PathVariable("configName") String configName, @RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size, Model uiModel) throws Exception { Configuration configuration = Configuration.findConfigurationsByNameEquals(configName).getSingleResult(); try { for (Transformer t:configuration.getTransformers()) t.removeOrphanedWiredTransformers(); // this is expensive and should go soon configuration.remove(); } catch (JpaSystemException e) { // assuming a possibly still exotically ocurring legacy error: a wire // of a *different* config uses this matcher, hence it would have a // foreign key into the void and complains so the matcher can't be // deleted and this config neither.. configuration.fixMatchersForAlienWire(); configuration.getWiring().clear(); configuration.merge(); configuration.removeTransformers(); configuration = Configuration.findConfigurationsByNameEquals(configName).getSingleResult(); configuration.remove(); } uiModel.asMap().clear(); uiModel.addAttribute("page", (page == null) ? "1" : page.toString()); uiModel.addAttribute("size", (size == null) ? "10" : size.toString()); return String.format("redirect:/%s_configs", configType); }
@UICommand @Override public String delete() { String copyName = getEntity().getName(); try { Library library = getEntity().getLibrary(); getDao().deleteEntity(getEntity()); showMessage("deletedEntity", "copy " + copyName); _libraryViewer.getContextualSearchResults().reload(); return _libraryViewer.viewEntity(library); } catch (JpaSystemException e) { if (e.contains(ConstraintViolationException.class)) { showMessage("cannotDeleteEntityInUse", "Copy " + copyName); return REDISPLAY_PAGE_ACTION_RESULT; } else { throw e; } } }
@Test(expected = JpaSystemException.class) public void test02_CreateYourEntity_DuplicateEntry() { LOGGER.info("Running: test02_CreateYourEntity"); YourEntity yourEntity = new YourEntity(); yourEntity.setEntityEmailAddress(USER_EMAIL); // Will Fail since it is not Unique ... yourEntity.setCredentials("password"); yourEntity.setEntityGivenName("Ro"); yourEntity.setEntitySurname("Bot"); yourEntity.setStatus(YourEntityStatus.ACTIVE); yourEntity.setYourEntityRoles(new HashSet<>()); yourEntity.setEntityProperties(new HashMap<>()); yourEntity.setYourEntityOrganizations(new HashSet<>()); identityProviderEntityManager.saveYourEntity(yourEntity); }
/** * Geef HTTP code 500 bij JPA fouten. * @param ex exception * @return fout omschrijving */ @ExceptionHandler(JpaSystemException.class) @ResponseBody @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) public ExceptionResponse handleOtherExceptions(final JpaSystemException ex) { LOG.warn("JPA exceptie opgetreden", ex); return new ExceptionResponse( "Databaseregels geschonden", "Ingevoerde gegevens komen al voor in de database of schenden integriteitsregels van de database"); }
@Test public void testSaveWithExistingEntityWithNullId() throws Exception { final RealizationEntity entity = getRealizationEntity(); final RealizationEntity saved = repository.saveAndFlush(entity); saved.setId(null); exception.expect(JpaSystemException.class); repository.saveAndFlush(saved); }
@Test public void testSaveWithExistingEntityWithNullId() throws Exception { final UserEntity entity = TestUtil.getUserEntity(); final UserEntity saved = repository.saveAndFlush(entity); saved.setId(null); exception.expect(JpaSystemException.class); repository.saveAndFlush(saved); }
@Test public void testSaveNullId() throws Exception { final CredentialsEntity entity = getCredentialsEntity(); entity.setId(null); exception.expect(JpaSystemException.class); exception.expectMessage(CredentialsEntity.class.getName()); repository.saveAndFlush(entity); }
@Test public void testSaveWithExistingEntityWithNullId() throws Exception { final ImageEntity entity = getImageEntity(); final ImageEntity saved = repository.saveAndFlush(entity); saved.setId(null); exception.expect(JpaSystemException.class); repository.saveAndFlush(saved); }
@Test public void testSaveWithExistingEntityWithNullId() throws Exception { final ExperimentEntity entity = getExperimentEntity(); final ExperimentEntity saved = repository.saveAndFlush(entity); saved.setId(null); exception.expect(JpaSystemException.class); repository.saveAndFlush(saved); }
@Test public void testSaveWithExistingEntityWithNullId() throws Exception { final DeterLabProjectEntity entity = Util.getDeterLabProjectEntity(); final DeterLabProjectEntity saved = repository.saveAndFlush(entity); saved.setId(null); exception.expect(JpaSystemException.class); repository.saveAndFlush(saved); }
@Test public void testSaveWithExistingEntityWithNullId() throws Exception { final DeterLabUserEntity entity = Util.getDeterlabUserEntity(); final DeterLabUserEntity saved = repository.saveAndFlush(entity); saved.setId(null); exception.expect(JpaSystemException.class); repository.saveAndFlush(saved); }
@Test(expected = JpaSystemException.class) public void testCreateStudentsWithNonUniqueIds() { Student student1 = new Student(); student1.setUniqueId("4113947bec18b7ad_1"); studentDao.create(student1); Student student2 = new Student(); student2.setUniqueId("4113947bec18b7ad_1"); studentDao.create(student2); }
@RequestMapping(path = "", method = RequestMethod.POST) @ResponseStatus(HttpStatus.OK) public CredentialView generate(InputStream inputStream) throws IOException { InputStream requestInputStream = new ByteArrayInputStream(ByteStreams.toByteArray(inputStream)); try { return legacyGenerationHandler.auditedHandlePostRequest(requestInputStream); } catch (JpaSystemException | DataIntegrityViolationException e) { requestInputStream.reset(); LOGGER.error( "Exception \"" + e.getMessage() + "\" with class \"" + e.getClass().getCanonicalName() + "\" while storing credential, possibly caused by race condition, retrying..."); return legacyGenerationHandler.auditedHandlePostRequest(requestInputStream); } }
@RequestMapping(path = "", method = RequestMethod.PUT) @ResponseStatus(HttpStatus.OK) public CredentialView set(@RequestBody BaseCredentialSetRequest requestBody) { requestBody.validate(); try { return auditedHandlePutRequest(requestBody); } catch (JpaSystemException | DataIntegrityViolationException e) { LOGGER.error( "Exception \"" + e.getMessage() + "\" with class \"" + e.getClass().getCanonicalName() + "\" while storing credential, possibly caused by race condition, retrying..."); return auditedHandlePutRequest(requestBody); } }
@Test(expected = JpaSystemException.class) public void testKewTypeBoBasicPersist() { KewTypeBoBuilder builder = new KewTypeBoBuilder("testType", "testNamespace"); dataObjectService.save(builder.build(), PersistenceOption.FLUSH); // try to persist the same information again, it should fail because of the unique constraint on name + namespace dataObjectService.save(builder.build(), PersistenceOption.FLUSH); }
@ExceptionHandler({ JpaSystemException.class}) protected ResponseEntity handleJpaSystemException( RuntimeException ex, WebRequest request) { String bodyOfResponse = ex.getCause().getCause().getMessage(); return handleExceptionInternal(ex, ResponseEntity .status(HttpStatus.BAD_REQUEST) .body(bodyOfResponse), new HttpHeaders(), HttpStatus.BAD_REQUEST, request); }
/** * Handle persistence exceptions thrown by handlers. Note that this method properly handles a null response being passed in. * * @param exception the exception * @param response the HTTP servlet response. * * @return the error information. */ @ExceptionHandler(value = {JpaSystemException.class, PersistenceException.class}) @ResponseBody public ErrorInformation handlePersistenceException(Exception exception, HttpServletResponse response) { // Persistence exceptions typically wrap the cause which is what we're interested in to know what specific problem happened so get the root // exception. Throwable throwable = getRootCause(exception); if (isDataTruncationException(throwable)) { // This is because the data being inserted was too large for a specific column in the database. When this happens, it will be due to a bad request. // Data truncation exceptions are thrown when we insert data that is too big for the column definition in MySQL. // On the other hand, Oracle throws only a generic JDBC exception, but has an error code we can check. // An alternative to using this database specific approach would be to define column lengths on the entities (e.g. @Column(length = 50)) // which should throw a consistent exception by JPA that could be caught here. The draw back to using this approach is that need to custom // configure all column widths for all fields and keep that in sync with our DDL. return getErrorInformationAndSetStatus(HttpStatus.BAD_REQUEST, throwable, response); } else if (isCausedByConstraintViolationException(exception)) { // A constraint violation exception will not typically be the root exception, but some exception in the chain. It is thrown when we try // to perform a database operation that violated a constraint (e.g. trying to delete a record that still has references to foreign keys // that exist, trying to insert duplicate keys, etc.). We are using ExceptionUtils to see if it exists somewhere in the chain. return getErrorInformationAndSetStatus(HttpStatus.BAD_REQUEST, new Exception("A constraint has been violated. Reason: " + throwable.getMessage()), response); } else { // For all other persistence exceptions, something is wrong that we weren't expecting so we'll return this as an internal server error. logError("A persistence error occurred.", exception); return getErrorInformationAndSetStatus(HttpStatus.INTERNAL_SERVER_ERROR, throwable == null ? new Exception("General Error") : throwable, response); } }
private static DataAccessException translateJpaSystemExceptionIfPossible( final DataAccessException accessException) { if (!(accessException instanceof JpaSystemException)) { return accessException; } final DataAccessException sql = searchAndTranslateSqlException(accessException); if (sql == null) { return accessException; } return sql; }
private void handle(APICreateLdapBindingMsg msg) { APICreateLdapBindingEvent evt = new APICreateLdapBindingEvent(msg.getId()); // account check SimpleQuery<AccountVO> sq = dbf.createQuery(AccountVO.class); sq.add(AccountVO_.uuid, SimpleQuery.Op.EQ, msg.getAccountUuid()); AccountVO avo = sq.find(); if (avo == null) { evt.setError(errf.instantiateErrorCode(LdapErrors.CANNOT_FIND_ACCOUNT, String.format("cannot find the specified account[uuid:%s]", msg.getAccountUuid()))); bus.publish(evt); return; } String ldapUseAsLoginName = LdapUtil.getLdapUseAsLoginName(); // bind op LdapTemplateContextSource ldapTemplateContextSource = readLdapServerConfiguration(); String fullDn = msg.getLdapUid(); if (!validateDnExist(ldapTemplateContextSource, fullDn)) { throw new OperationFailureException(errf.instantiateErrorCode(LdapErrors.UNABLE_TO_GET_SPECIFIED_LDAP_UID, String.format("cannot find dn[%s] on ldap server[Address:%s, BaseDN:%s].", fullDn, String.join(", ", ldapTemplateContextSource.getLdapContextSource().getUrls()), ldapTemplateContextSource.getLdapContextSource().getBaseLdapPathAsString()))); } try { evt.setInventory(bindLdapAccount(msg.getAccountUuid(), fullDn)); logger.info(String.format("create ldap binding[ldapUid=%s, ldapUseAsLoginName=%s] success", fullDn, ldapUseAsLoginName)); } catch (JpaSystemException e) { if (e.getRootCause() instanceof MySQLIntegrityConstraintViolationException) { evt.setError(errf.instantiateErrorCode(LdapErrors.BIND_SAME_LDAP_UID_TO_MULTI_ACCOUNT, "The ldap uid has been bound to an account. ")); } else { throw e; } } bus.publish(evt); }
@Override public UsedIpInventory reserveIp(IpRangeInventory ipRange, String ip) { try { UsedIpVO vo = new UsedIpVO(ipRange.getUuid(), ip); vo.setIpInLong(NetworkUtils.ipv4StringToLong(ip)); String uuid = ipRange.getUuid() + ip; uuid = UUID.nameUUIDFromBytes(uuid.getBytes()).toString().replaceAll("-", ""); vo.setUuid(uuid); vo.setL3NetworkUuid(ipRange.getL3NetworkUuid()); vo.setNetmask(ipRange.getNetmask()); vo.setGateway(ipRange.getGateway()); vo = dbf.persistAndRefresh(vo); return UsedIpInventory.valueOf(vo); } catch (JpaSystemException e) { if (e.getRootCause() instanceof MySQLIntegrityConstraintViolationException) { logger.debug(String.format("Concurrent ip allocation. " + "Ip[%s] in ip range[uuid:%s] has been allocated, try allocating another one. " + "The error[Duplicate entry] printed by jdbc.spi.SqlExceptionHelper is no harm, " + "we will try finding another ip", ip, ipRange.getUuid())); logger.trace("", e); } else { throw e; } } return null; }
private ResponseBuilder processBadRequestExceptions(final Exception ex) { // This exception might be raised by Flowable (if enabled) Class<?> ibatisPersistenceException = null; try { ibatisPersistenceException = Class.forName("org.apache.ibatis.exceptions.PersistenceException"); } catch (ClassNotFoundException e) { // ignore } if (ex instanceof WorkflowException) { return builder(ClientExceptionType.Workflow, ExceptionUtils.getRootCauseMessage(ex)); } else if (ex instanceof PersistenceException) { return builder(ClientExceptionType.GenericPersistence, ExceptionUtils.getRootCauseMessage(ex)); } else if (ibatisPersistenceException != null && ibatisPersistenceException.isAssignableFrom(ex.getClass())) { return builder(ClientExceptionType.Workflow, "Currently unavailable. Please try later."); } else if (ex instanceof JpaSystemException) { return builder(ClientExceptionType.DataIntegrityViolation, ExceptionUtils.getRootCauseMessage(ex)); } else if (ex instanceof ConfigurationException) { return builder(ClientExceptionType.InvalidConnIdConf, ExceptionUtils.getRootCauseMessage(ex)); } else if (ex instanceof ParsingValidationException) { return builder(ClientExceptionType.InvalidValues, ExceptionUtils.getRootCauseMessage(ex)); } else if (ex instanceof MalformedPathException) { return builder(ClientExceptionType.InvalidPath, ExceptionUtils.getRootCauseMessage(ex)); } return null; }
/** * Duplicate username test method for * {@link com.impetus.ankush.service.impl.UserManagerImpl#saveUser(com.impetus.ankush.common.domain.model.User)} * . * @throws UserExistsException */ @Test(expected=UserExistsException.class) public void testSaveUserJPAException() throws UserExistsException { ((UserManagerImpl)userManager).setPasswordEncoder(null); EasyMock.expect(userDao.saveUser(user)).andThrow(new JpaSystemException(new PersistenceException())); EasyMock.replay(userDao); userManager.saveUser(user); fail("should throw an exception"); }
@Test(expected = JpaSystemException.class) public void primaryKeyExceptionTest() { Permission newPermission = new Permission(); permissionRepository.save(newPermission); }