下面列出了怎么用org.springframework.orm.jpa.JpaSystemException的API类实例代码及写法,或者点击链接到github查看源代码。
private VmNicVO persistAndRetryIfMacCollision(VmNicVO vo) {
int tries = 5;
while (tries-- > 0) {
try {
return dbf.persistAndRefresh(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;
}
/**
* Constructor.
*
* @param dataServiceRetryProperties retry properties
*/
public DataServiceRetryAspect(final DataServiceRetryProperties dataServiceRetryProperties) {
this.retryTemplate = new RetryTemplate();
this.retryTemplate.setRetryPolicy(
new SimpleRetryPolicy(
dataServiceRetryProperties.getNoOfRetries(),
new ImmutableMap.Builder<Class<? extends Throwable>, Boolean>()
.put(CannotGetJdbcConnectionException.class, true)
.put(CannotAcquireLockException.class, true)
.put(DeadlockLoserDataAccessException.class, true)
.put(OptimisticLockingFailureException.class, true)
.put(PessimisticLockingFailureException.class, true)
.put(ConcurrencyFailureException.class, true)
// Will this work for cases where the write queries timeout on the client?
.put(QueryTimeoutException.class, true)
.put(TransientDataAccessResourceException.class, true)
.put(JpaSystemException.class, true)
.build()
)
);
final ExponentialBackOffPolicy backOffPolicy = new ExponentialBackOffPolicy();
backOffPolicy.setInitialInterval(dataServiceRetryProperties.getInitialInterval());
backOffPolicy.setMaxInterval(dataServiceRetryProperties.getMaxInterval());
this.retryTemplate.setBackOffPolicy(backOffPolicy);
}
/**
* 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(err(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 = ldapUtil.readLdapServerConfiguration();
String fullDn = msg.getLdapUid();
if (!ldapUtil.validateDnExist(ldapTemplateContextSource, fullDn)) {
throw new OperationFailureException(err(LdapErrors.UNABLE_TO_GET_SPECIFIED_LDAP_UID,
"cannot find dn[%s] on LDAP/AD 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(err(LdapErrors.BIND_SAME_LDAP_UID_TO_MULTI_ACCOUNT,
"The ldap uid has been bound to an account. "));
} else {
throw e;
}
}
bus.publish(evt);
}
private UsedIpInventory reserveIpv6(IpRangeVO ipRange, String ip) {
try {
UsedIpVO vo = new UsedIpVO();
//vo.setIpInLong(NetworkUtils.ipv4StringToLong(ip));
String uuid = ipRange.getUuid() + ip;
uuid = UUID.nameUUIDFromBytes(uuid.getBytes()).toString().replaceAll("-", "");
vo.setUuid(uuid);
vo.setIpRangeUuid(ipRange.getUuid());
vo.setIp(IPv6NetworkUtils.getIpv6AddressCanonicalString(ip));
vo.setL3NetworkUuid(ipRange.getL3NetworkUuid());
vo.setNetmask(ipRange.getNetmask());
vo.setGateway(ipRange.getGateway());
vo.setIpVersion(IPv6Constants.IPv6);
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 UsedIpInventory reserveIpv4(IpRangeVO ipRange, String ip, boolean allowDuplicatedAddress) {
try {
UsedIpVO vo = new UsedIpVO(ipRange.getUuid(), ip);
vo.setIpInLong(NetworkUtils.ipv4StringToLong(ip));
String uuid;
if (allowDuplicatedAddress) {
uuid = Platform.getUuid();
} else {
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.setIpVersion(IPv6Constants.IPv4);
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;
}
}
@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);
}
/**
* 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");
}