Java 类javax.persistence.RollbackException 实例源码

项目:cf-mta-deploy-service    文件:ConfigurationSubscriptionDtoDao.java   
public ConfigurationSubscriptionDto update(long id, ConfigurationSubscriptionDto delta)
    throws ConflictException, NotFoundException {
    try {
        return new TransactionalExecutor<ConfigurationSubscriptionDto>(createEntityManager()).execute((manager) -> {

            ConfigurationSubscriptionDto existingSubscription = findInternal(id, manager);
            if (existingSubscription == null) {
                throw new NotFoundException(Messages.CONFIGURATION_SUBSCRIPTION_NOT_FOUND, id);
            }
            ConfigurationSubscriptionDto result = merge(existingSubscription, delta);
            manager.merge(result);
            return result;

        });
    } catch (RollbackException e) {
        ConfigurationSubscriptionDto subscription = merge(find(id), delta);
        throw new ConflictException(e, Messages.CONFIGURATION_SUBSCRIPTION_ALREADY_EXISTS, subscription.getMtaId(),
            subscription.getAppName(), subscription.getResourceName(), subscription.getSpaceId());
    }
}
项目:mycore    文件:MCRURNGranularRESTRegistrationTask.java   
private static void endTransaction(EntityTransaction tx) {
    if (tx != null && tx.isActive()) {
        if (tx.getRollbackOnly()) {
            tx.rollback();
        } else {
            try {
                tx.commit();
            } catch (RollbackException e) {
                if (tx.isActive()) {
                    tx.rollback();
                }
                throw e;
            }
        }
    }
}
项目:mycore    文件:MCRJPATestCase.java   
protected void endTransaction() {
    entityManager.ifPresent(em -> {
        EntityTransaction tx = em.getTransaction();
        if (tx != null && tx.isActive()) {
            if (tx.getRollbackOnly()) {
                tx.rollback();
            } else {
                try {
                    tx.commit();
                } catch (RollbackException e) {
                    if (tx.isActive()) {
                        tx.rollback();
                    }
                    throw e;
                }
            }
        }
    });
}
项目:europa    文件:ContainerRepoDb.java   
public boolean incrementSyncCount(String domain, String id, long currentCount) {
    try {
        _main.updateItem(getHashKey(domain), id.toLowerCase())
            .set("syc", currentCount+1)
            .when((expr) -> {
                    if ( 0 == currentCount ) {
                        return expr.or(expr.eq("syc", 0),
                                expr.and(expr.exists("id"), expr.not(expr.exists("syc"))));
                    } else {
                        return expr.eq("syc", currentCount);
                    }
                });
        return true;
    } catch ( RollbackException ex ) {
        return false;
    }
}
项目:europa    文件:RegistryBlobDb.java   
public void addPart(String blobId, int partIndex, RegistryBlobPart partId, byte[] oldMDState, byte[] newMDState)
    throws EntityNotFoundException, ConcurrentModificationException
{
    try {
        _main.updateItem(blobId, null)
            .listSet(ATTR_PART_IDS, partIndex, AttrType.MAP, partId)
            .set(ATTR_MD_ENCODED_STATE, AttrType.BIN, newMDState)
            .when((expr) -> expr.and(
                      expr.exists(ATTR_BLOB_ID),
                      ( null == oldMDState )
                      ? expr.not(expr.exists(ATTR_MD_ENCODED_STATE))
                      : expr.eq(ATTR_MD_ENCODED_STATE, oldMDState)));
    } catch ( RollbackException ex ) {
        // Doesn't exist, then throw EntityNotFoundException?
        RegistryBlob blob = _main.getItemOrThrow(blobId, null);
        throw new ConcurrentModificationException(
            "Expected mdState="+(null==oldMDState?"null":printHexBinary(oldMDState))+", but got="+
            (null == blob.getMdEncodedState()?"null":printHexBinary(blob.getMdEncodedState())));
    }
}
项目:europa    文件:RegistryBlobDb.java   
public void finishUpload(String blobId, byte[] currentMDState, String digest, long size, String mediaType) {
    try {
        UpdateItemBuilder<RegistryBlob> builder = _main.updateItem(blobId, null)
            .remove(ATTR_PART_IDS)
            .remove(ATTR_MD_ENCODED_STATE)
            .remove(ATTR_UPLOAD_ID)
            .set(ATTR_DIGEST, digest.toLowerCase())
            .set(ATTR_SIZE, size);
        if ( null != mediaType ) {
            builder.set(ATTR_MEDIA_TYPE, mediaType);
        }
        builder.when((expr) -> expr.eq(ATTR_MD_ENCODED_STATE, currentMDState));
    } catch ( RollbackException ex ) {
        throw new ConcurrentModificationException(
            "attempt to finish upload of "+blobId+", but the digest state did not match");
    }
}
项目:europa    文件:RegistryBlobDb.java   
public Long addReference(String digest, String manifestId) {
    digest = digest.toLowerCase();
    for ( int retry=0;;retry++ ) {
        RegistryBlob blob = getRegistryBlobByDigest(digest);
        if ( null == blob ) return null;
        try {
            return _main.updateItem(blob.getBlobId(), null)
                .setAdd(ATTR_MANIFEST_IDS, AttrType.STR, manifestId)
                .returnAllNew()
                .when((expr) -> expr.exists(ATTR_BLOB_ID))
                .getSize();
        } catch ( RollbackException ex ) {
            log.info(ex.getMessage(), ex);
            // Give up!
            if ( retry > 10 ) return null;
            continue;
        }
    }
}
项目:oldSyncopeIdM    文件:UserRequestController.java   
@RequestMapping(method = RequestMethod.POST,
value = "/create")
public UserRequestTO create(@RequestBody final UserTO userTO)
        throws UnauthorizedRoleException {

    if (!isCreateAllowedByConf()) {
        LOG.error("Create requests are not allowed");

        throw new UnauthorizedRoleException(-1L);
    }

    LOG.debug("Request user create called with {}", userTO);

    try {
        dataBinder.testCreate(userTO);
    } catch (RollbackException e) {
    }

    UserRequest request = new UserRequest();
    request.setUserTO(userTO);
    request = userRequestDAO.save(request);

    return dataBinder.getUserRequestTO(request);
}
项目:oldSyncopeIdM    文件:UserRequestController.java   
@PreAuthorize("isAuthenticated()")
@RequestMapping(method = RequestMethod.POST,
value = "/update")
public UserRequestTO update(@RequestBody final UserMod userMod)
        throws NotFoundException, UnauthorizedRoleException {

    LOG.debug("Request user update called with {}", userMod);

    try {
        dataBinder.testUpdate(userMod);
    } catch (RollbackException e) {
    }

    UserRequest request = new UserRequest();
    request.setUserMod(userMod);
    request = userRequestDAO.save(request);

    return dataBinder.getUserRequestTO(request);
}
项目:oldSyncopeIdM    文件:UserRequestController.java   
@PreAuthorize("isAuthenticated()")
@RequestMapping(method = RequestMethod.POST,
value = "/delete")
public UserRequestTO delete(@RequestBody final Long userId)
        throws NotFoundException, UnauthorizedRoleException {

    LOG.debug("Request user delete called with {}", userId);

    try {
        dataBinder.testDelete(userId);
    } catch (RollbackException e) {
    }

    UserRequest request = new UserRequest();
    request.setUserId(userId);
    request = userRequestDAO.save(request);

    return dataBinder.getUserRequestTO(request);
}
项目:ViTA    文件:DocumentService.java   
/**
 * Renames the current document to the given name.
 *
 * @param renameRequest - the renaming request including id and new name.
 * @return a response with no content if renaming was successful, HTTP 404 if document was not
 *         found or 500 if an error occurred.
 */
@PUT
@Consumes(MediaType.APPLICATION_JSON)
public Response putDocument(DocumentRenameRequest renameRequest) {
  Response response = null;
  try {
    Document affectedDocument = documentDao.findById(id);
    affectedDocument.getMetadata().setTitle(renameRequest.getName());
    affectedDocument.getMetadata().setIsUserDefinedTitle(true);
    documentDao.update(affectedDocument);

    response = Response.noContent().build();
  } catch (EntityNotFoundException enfe) {
    throw new WebApplicationException(enfe, Response.status(Response.Status.NOT_FOUND).build());
  } catch (RollbackException re) {
    throw new WebApplicationException(re);
  }
  return response;
}
项目:tekoporu-postgresql    文件:UsuarioEditMB.java   
@ExceptionHandler
public void tratarHibernatePostgreSQL(RollbackException e) {
    PersistenceException persistenceException = (PersistenceException) e
            .getCause();
    /*
     * Desde aquí ya no es estándar JEE6, estas son clases específicas de
     * Hibernate y PostgreSQL dependiendo del proveedor JPA y del motor que
     * se utilice esto habrá que adaptar
     */
    ConstraintViolationException constraintViolationException = (ConstraintViolationException) persistenceException
            .getCause();
    BatchUpdateException batchUpdateException = (BatchUpdateException) constraintViolationException
            .getCause();
    Exception psqlException = batchUpdateException.getNextException();
    String msg = psqlException.getLocalizedMessage();
    logger.error("Error al realizar el update: " + msg);
    FacesContext.getCurrentInstance().addMessage(null,
            new FacesMessage(FacesMessage.SEVERITY_ERROR, msg, null));
}
项目:oscm    文件:TransactionInvocationHandlersTest.java   
public void commit() {
    status = Status.STATUS_NO_TRANSACTION;
    stubCalls.add("commit()");
    if (failCommit) {
        throw new RollbackException();
    }
}
项目:oscm    文件:TransactionInvocationHandlersTest.java   
@Override
public void commit() {
    status = Status.STATUS_NO_TRANSACTION;
    stubCalls.add("commit()");
    if (failCommit) {
        throw new RollbackException();
    }
}
项目:cf-mta-deploy-service    文件:ConfigurationSubscriptionDtoDao.java   
public ConfigurationSubscriptionDto add(ConfigurationSubscriptionDto subscription) throws ConflictException {
    try {
        return new TransactionalExecutor<ConfigurationSubscriptionDto>(createEntityManager()).execute((manager) -> {

            manager.persist(subscription);
            return subscription;

        });
    } catch (RollbackException e) {
        throw new ConflictException(e, Messages.CONFIGURATION_SUBSCRIPTION_ALREADY_EXISTS, subscription.getMtaId(),
            subscription.getAppName(), subscription.getResourceName(), subscription.getSpaceId());
    }
}
项目:cf-mta-deploy-service    文件:ConfigurationEntryDtoDao.java   
public ConfigurationEntryDto add(ConfigurationEntryDto entry) throws ConflictException {
    try {
        return new TransactionalExecutor<ConfigurationEntryDto>(createEntityManager()).execute((manager) -> {

            manager.persist(entry);
            return entry;

        });
    } catch (RollbackException e) {
        throw new ConflictException(e, Messages.CONFIGURATION_ENTRY_ALREADY_EXISTS, entry.getProviderNid(), entry.getProviderId(),
            entry.getProviderVersion(), entry.getTargetOrg(), entry.getTargetSpace());
    }
}
项目:cf-mta-deploy-service    文件:ContextExtensionDao.java   
public ContextExtension add(ContextExtension entry) throws ConflictException {
    try {
        return new TransactionalExecutor<ContextExtension>(createEntintyManager()).execute((manager) -> {

            manager.persist(entry);
            return entry;

        });
    } catch (RollbackException e) {
        throw new ConflictException(e, Messages.CONTEXT_EXTENSION_ENTRY_ALREADY_EXISTS, entry.getProcessId(), entry.getName(),
            entry.getValue());
    }
}
项目:comms-router    文件:RollbackExceptionMapper.java   
@Override
protected ExceptionPresentation getExceptionPresentation(RollbackException exception) {
  if (exception.getCause() != null) {
    return new ExceptionPresentation(exception.getCause());
  }
  return super.getExceptionPresentation(exception);
}
项目:spring4-understanding    文件:JpaTransactionManagerTests.java   
@Test
public void testTransactionCommitWithRollbackException() {
    given(manager.getTransaction()).willReturn(tx);
    given(tx.getRollbackOnly()).willReturn(true);
    willThrow(new RollbackException()).given(tx).commit();

    final List<String> l = new ArrayList<String>();
    l.add("test");

    assertTrue(!TransactionSynchronizationManager.hasResource(factory));
    assertTrue(!TransactionSynchronizationManager.isSynchronizationActive());

    try {
        Object result = tt.execute(new TransactionCallback() {
            @Override
            public Object doInTransaction(TransactionStatus status) {
                assertTrue(TransactionSynchronizationManager.hasResource(factory));
                EntityManagerFactoryUtils.getTransactionalEntityManager(factory).flush();
                return l;
            }
        });
        assertSame(l, result);
    }
    catch (TransactionSystemException tse) {
        // expected
        assertTrue(tse.getCause() instanceof RollbackException);
    }

    assertTrue(!TransactionSynchronizationManager.hasResource(factory));
    assertTrue(!TransactionSynchronizationManager.isSynchronizationActive());

    verify(manager).flush();
    verify(manager).close();
}
项目:ci-spring-boot    文件:TaskRepositoryTest.java   
@Test(expected= TransactionSystemException.class)
public void shouldBeFailToUpdateWithoutDescription() {
    try {
        Task task = taskRepository.save(new Task("Test"));
        task.setDescription(null);
        taskRepository.save(task);
    } catch (TransactionSystemException e) {
        ((ConstraintViolationException)((RollbackException)e.getCause()).getCause()).getConstraintViolations().forEach(c -> {
            c.getPropertyPath().forEach(f -> Assert.assertEquals("description", f.getName()));
        });
        throw e;
    }
}
项目:continuous-delivery-demo    文件:GlobalControllerExceptionHandler.java   
@ExceptionHandler(Exception.class)
@ResponseBody
public ResponseEntity<?> handleErrors(Exception ex) {
    if (ex.getCause() instanceof RollbackException
            && ex.getCause().getCause() instanceof ConstraintViolationException) {
        ConstraintViolationException constraintViolationException = (ConstraintViolationException) ex.getCause().getCause();
        return new ResponseEntity<List<ValidationMessage>>(getValidationErrorResponse(constraintViolationException), HttpStatus.BAD_REQUEST);
    } else {
        LOG.error("Got unknown error", ex);
        // fallback to server error
        return new ResponseEntity<Message>(new Message(ex.getMessage()), HttpStatus.INTERNAL_SERVER_ERROR);
    }
}
项目:jpasecurity    文件:EnumTest.java   
@Test
public void updateFails() {
    Task updateTask = entityManager.createQuery("SELECT t FROM Task t", Task.class).getSingleResult();

    try {
        entityManager.getTransaction().begin();
        updateTask.setStatus(null);
        entityManager.getTransaction().commit();
        fail("expected SecurityException");
    } catch (RollbackException e) {
        assertThat(e.getCause(), is(instanceOf(SecurityException.class)));
    }
}
项目:java-persistence    文件:DdbIndex.java   
private boolean updateItem(IndexKey key, String updateExpression, String conditionalExpression,
                           Map<String, String> expressionNames, Map<String, Object> expressionValues)
{
    try {
        updateItem(new UpdateItemSpec()
                   .withPrimaryKey(toPrimaryKey(key))
                   .withUpdateExpression(updateExpression)
                   .withConditionExpression(conditionalExpression)
                   .withNameMap(expressionNames)
                   .withValueMap(expressionValues));
        return true;
    } catch ( RollbackException ex ) {
        return false;
    }
}
项目:java-persistence    文件:DdbIndex.java   
private <V> V updateItem(UpdateItemSpec updateItemSpec, Class<V> type) {
    try {
        return maybeBackoff(false, () ->
                            fromItem(_encryption.decrypt(_updateItem.updateItem(updateItemSpec).getItem()), type));
    } catch ( ConditionalCheckFailedException ex ) {
        throw new RollbackException(ex);
    }
}
项目:java-persistence    文件:UpdateItemBuilderImpl.java   
public <V> V when(FilterCondFn updateCondFn, Class<V> type) throws RollbackException {
    FilterCondExprImpl condExpr = (FilterCondExprImpl)updateCondFn.run(new FilterCondBuilderImpl(_encryption));
    if ( null != condExpr ) {
        _spec.withConditionExpression(condExpr.eval(this::addExprName, this::addExprValue));
    }
    return always(type);
}
项目:java-persistence    文件:MysqlIndex.java   
@Override
public void deleteItem(Object hk, Object rk, FilterCondFn filterCondFn) throws RollbackException {
    MysqlFilterCondExpr expr = ( null == filterCondFn ) ? null :
        (MysqlFilterCondExpr)filterCondFn.run(_condBuilder);
    int count = deleteItems(expr, new IndexKey().withHashKey(hk).withRangeKey(rk));
    if ( null != expr && count < 1 ) {
        throw new RollbackException();
    }
}
项目:java-persistence    文件:MysqlUpdateItemBuilder.java   
@Override
public <V> V when(FilterCondFn updateCondFn, Class<V> type) throws RollbackException {
    MysqlFilterCondExpr condExpr = null;
    if ( null != updateCondFn ) {
        condExpr = (MysqlFilterCondExpr)
            updateCondFn.run(new MysqlFilterCondBuilder());
    }

    return _updateItem.updateItem(_hk, _rk, type, _returnValue, _defaultJson, this::updateExpr, condExpr);
}
项目:invesdwin-context-persistence    文件:SimpleTestDaoTest.java   
@Test
@Ignore("duplicate deletion throws exception in comparison to hibernate")
public void testDeleteWithTransaction() {
    try {
        new TransactionalAspectMethods().testDeleteWithTransaction();
    } catch (final TransactionSystemException e) {
        Assertions.assertThat(Throwables.isCausedByType(e, RollbackException.class)).isTrue();
    }
}
项目:invesdwin-context-persistence    文件:SimpleTestDaoTest.java   
@Test
public void testDeleteWithTransaction() {
    try {
        new TransactionalAspectMethods().testDeleteWithTransaction();
    } catch (final TransactionSystemException e) {
        Assertions.assertThat(Throwables.isCausedByType(e, RollbackException.class)).isTrue();
    }
}
项目:invesdwin-context-persistence    文件:TestDaoTest.java   
@Test
public void testDeleteWithTransaction() {
    try {
        new TransactionalAspectMethods().testDeleteWithTransaction();
    } catch (final TransactionSystemException e) {
        Assertions.assertThat(Throwables.isCausedByType(e, RollbackException.class)).isTrue();
    }
}
项目:invesdwin-context-persistence    文件:SimpleTestDaoTest.java   
@Ignore("Dunno why sometimes em.persist() worx and sometimes it doesnt...")
@Test
public void testDeleteWithTransaction() {
    try {
        new TransactionalAspectMethods().testDeleteWithTransaction();
    } catch (final TransactionSystemException e) {
        Assertions.assertThat(Throwables.isCausedByType(e, RollbackException.class)).isTrue();
    }
}
项目:europa    文件:DeleteAuthToken.java   
public Object get(AjaxRequest ajaxRequest, EuropaRequestContext requestContext)
{
    String token = ajaxRequest.getParam("token", true); //throw if missing
    try {
        _tokenAuthDb.deleteToken(requestContext.getRequesterDomain(), token);
    } catch(RollbackException rbe) {
        throw(new AjaxClientException("Cannot Delete active Token", AjaxErrors.Codes.TokenIsActive, 400));
    }
    return JsonSuccess.Success;
}
项目:europa    文件:PipelineDb.java   
public void setContainerRepo(String pipelineId, String domain, String containerRepoId) {
    pipelineId = pipelineId.toLowerCase();
    try {
        _main.updateItem(pipelineId, CID_FOR_PIPELINE)
            .set("dom", domain)
            .set("crid", containerRepoId)
            .when((expr) -> expr.exists("id"));
    } catch ( RollbackException ex ) {
        throw new EntityNotFoundException("Invalid pipelineId="+pipelineId);
    }
}
项目:europa    文件:PipelineDb.java   
public void movePipelineComponent(String pipelineId, String componentId, String beforeComponentId) {
    pipelineId = pipelineId.toLowerCase();
    long idx = allocateIdxBefore(pipelineId, beforeComponentId);
    try {
        _main.updateItem(pipelineId, componentId)
            .set("idx", idx)
            .when((expr) -> expr.exists("id"));
    } catch ( RollbackException ex ) {
        throw new EntityNotFoundException("Invalid pipelineId="+pipelineId+" componentId="+componentId);
    }
}
项目:europa    文件:PipelineDb.java   
private void incrementIdx(PKIdx item, long amount) {
    try {
        _main.updateItem(item.id, item.cid)
            .increment("idx", amount)
            .when((expr) -> expr.exists("idx"));
    } catch ( RollbackException ex ){}
}
项目:europa    文件:TokenAuthDb.java   
public void deleteToken(String domain, String token)
    throws RollbackException
{
    _main.deleteItem(token, null,
                     (expr) -> expr.and(expr.eq("stat", "INACTIVE"),
                                        expr.eq("dom", domain.toLowerCase())));
}
项目:europa    文件:RegistryBlobDb.java   
public void setUploadId(String blobId, String uploadId) {
    try {
        _main.updateItem(blobId, null)
            .set(ATTR_UPLOAD_ID, AttrType.STR, uploadId)
            .when((expr) -> expr.exists(ATTR_BLOB_ID));
    } catch ( RollbackException ex ) {
        throw new EntityNotFoundException("blobId="+blobId+" does not exist");
    }
}
项目:europa    文件:RegistryBlobDb.java   
public void removeReference(String digest, String manifestId) {
    digest = digest.toLowerCase();
    for ( PageIterator it : new PageIterator() ) {
        for ( RegistryBlob blob : _byDigest.queryItems(digest, it).list() ) {
            try {
                _main.updateItem(blob.getBlobId(), null)
                    .setRemove(ATTR_MANIFEST_IDS, AttrType.STR, manifestId)
                    .when((expr) -> expr.exists(ATTR_BLOB_ID));
            } catch ( RollbackException ex ) {
                // ignored, just don't want to create a "blank" record.
            }
        }
    }
}
项目:development    文件:TransactionInvocationHandlersTest.java   
public void commit() {
    status = Status.STATUS_NO_TRANSACTION;
    stubCalls.add("commit()");
    if (failCommit) {
        throw new RollbackException();
    }
}
项目:development    文件:TransactionInvocationHandlersTest.java   
@Override
public void commit() {
    status = Status.STATUS_NO_TRANSACTION;
    stubCalls.add("commit()");
    if (failCommit) {
        throw new RollbackException();
    }
}