public Object call(Callable<Object> callable, IInvocationHandler.IInvocationCtx ctx) throws Exception { try { return callable.call(); } catch (Exception ex) { if (ctx.isApplicationException(ex)) { if (hasRollbackAnnotation(ex)) { ctx.getTransactionManager().setRollbackOnly(); } throw ex; } else { ctx.getTransactionManager().setRollbackOnly(); throw setCause(new EJBTransactionRolledbackException( "Rollback due to exception.", ex)); } } }
@Test(expected = ConcurrentModificationException.class) public void writeReview_ConcurrentModificationException() throws Exception { // given initProduct(1l); initProductReview(2l); productReview.setPlatformUser(currentUser); doReturn(product).when(dm).getReference(Product.class, 1l); doThrow(new EJBTransactionRolledbackException()).when(dm).flush(); // when try { reviewBean.writeReview(productReview, Long.valueOf(product.getKey())); // then fail(); } catch (Exception e) { throw e; } }
@RolesAllowed("PLATFORM_OPERATOR") public void setDefaultAdapter(BillingAdapter billingAdapter) throws EJBTransactionRolledbackException { ArgumentValidator.notNull("Billing adapter", billingAdapter); List<BillingAdapter> adapters = getAll(); for (BillingAdapter ba : adapters) { if (ba.getBillingIdentifier().equals( billingAdapter.getBillingIdentifier())) { ba.setDefaultAdapter(true); } else { ba.setDefaultAdapter(false); } } ds.flush(); }
@Override public Response setDefaultBillingAdapter(POBillingAdapter poBillingAdapter) throws SaaSApplicationException { Response response = new Response(); BillingAdapter adapter = billingAdapter.get(poBillingAdapter .getBillingIdentifier()); if (adapter == null) { sessionCtx.setRollbackOnly(); throw new ObjectNotFoundException(ClassEnum.BILLING_ADAPTER, poBillingAdapter.getBillingIdentifier()); } else { BasePOAssembler.verifyVersionAndKey(adapter, poBillingAdapter); try { billingAdapter.setDefaultAdapter(adapter); } catch (EJBTransactionRolledbackException e) { sessionCtx.setRollbackOnly(); throw new SaaSApplicationException(e); } } return response; }
/** * Adds a new entity to the underlying collection. * @param entity The entity to add * @return HTTP 201 Created with a Location header pointing to the new * entity, or HTTP 409 Conflict if an entity with the same key already * exists. */ @POST @Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) public Response add(TEntity entity) { try { requireRole(addRole); collection.insert(entity); // flush changes so Exception can be caught in this block // - otherwise exception won't appear until end of request. collection.flush(); Integer id = collection.getId(entity); // return the correct Location header. URI location = uriInfo.getAbsolutePathBuilder().path(id.toString()).build(); return Response.created(location).build(); } catch (EJBTransactionRolledbackException e) { // if a duplicate key error happened, return HTTP 409 conflict Exception cause = e.getCausedByException(); if (cause != null) { Throwable rootCause = cause.getCause(); if (rootCause != null && rootCause.getClass() == PersistenceException.class) { return Response.status(Status.CONFLICT).build(); } } throw e; } }
@Test public void startPasswordRecovery_EJBTransactionFailed() throws Exception { // given doThrow(new EJBTransactionRolledbackException()).when( passwordRecoverybean.dm).flush(); // when passwordRecoverybean.startPasswordRecovery(userId, marketplaceId); // then verify(passwordRecoverybean, never()).sendPasswordRecoveryMails( any(PlatformUser.class), any(EmailType.class), anyString(), any(Object[].class)); }
@Test public void completePasswordRecovery_EJBTransactionFailed() throws Exception { // given doThrow(new EJBTransactionRolledbackException()).when( passwordRecoverybean.dm).flush(); // when boolean result = passwordRecoverybean.completePasswordRecovery(userId, password_6letter); // then verify(passwordRecoverybean, never()).sendPasswordRecoveryMails( any(PlatformUser.class), any(EmailType.class), anyString(), any(Object[].class)); assertEquals(false, result); }
private boolean isTransactionRolledBack(Throwable th) { Throwable cause = th.getCause(); while (cause != null && !cause.equals(th)) { if (cause instanceof EJBTransactionRolledbackException) { return true; } return isTransactionRolledBack(cause); } return false; }
@Test public void testHANDLER_WITHINTX_Exception() throws Exception { final Exception root = new IOException(); try { TransactionInvocationHandlers.HANDLER_WITHINTX.call( callableException(root), ctxStub); fail("Exception expected"); } catch (EJBTransactionRolledbackException ejbex) { assertSame(root, ejbex.getCause()); assertSame(root, ejbex.getCausedByException()); } assertEquals(Arrays.asList("call()", "setRollbackOnly()"), stubCalls); }
@Test public void testHANDLER_NEWTX_Positive_MarkedRollback() throws Exception { try { TransactionInvocationHandlers.HANDLER_NEWTX.call( callableMarkRollback(), ctxStub); fail("Exception expected"); } catch (EJBTransactionRolledbackException ejbex) { assertNull(ejbex.getCause()); assertNull(ejbex.getCausedByException()); } assertEquals(Arrays.asList("begin()", "call()", "setRollbackOnly()", "rollback()"), stubCalls); }
@Test public void testHANDLER_NEWTX_CommitFailed1() throws Exception { failCommit = true; try { TransactionInvocationHandlers.HANDLER_NEWTX.call( callableReturns(new Object()), ctxStub); fail("Exception expected"); } catch (EJBTransactionRolledbackException ejbex) { } assertEquals(Arrays.asList("begin()", "call()", "commit()"), stubCalls); }
@Test public void testHANDLER_NEWTX_CommitFailed2() throws Exception { failCommit = true; ctxStubIsApplicationException = true; Exception root = new IOException(); try { TransactionInvocationHandlers.HANDLER_NEWTX.call( callableException(root), ctxStub); fail("Exception expected"); } catch (EJBTransactionRolledbackException ex) { } assertEquals(Arrays.asList("begin()", "call()", "commit()"), stubCalls); }
public Object call(Callable<Object> callable, IInvocationHandler.IInvocationCtx ctx) throws Exception { final Object result; ctx.getTransactionManager().begin(); try { result = callable.call(); } catch (Exception ex) { if (ctx.isApplicationException(ex)) { if (hasRollbackAnnotation(ex) || ctx.getTransactionManager().getStatus() == Status.STATUS_MARKED_ROLLBACK) { ctx.getTransactionManager().rollback(); } else { commit(ctx); } throw ex; } ctx.getTransactionManager().rollback(); throw setCause(new EJBException(ex)); } catch (Error err) { // Required for AssertErrors thrown by JUnit4 assertions: ctx.getTransactionManager().rollback(); throw err; } if (ctx.getTransactionManager().getStatus() == Status.STATUS_MARKED_ROLLBACK) { ctx.getTransactionManager().rollback(); throw new EJBTransactionRolledbackException(); } commit(ctx); return result; }
private void commit(IInvocationHandler.IInvocationCtx ctx) { try { ctx.getTransactionManager().commit(); } catch (Exception ex) { throw setCause(new EJBTransactionRolledbackException( "Commit failed.", ex)); } }
@RolesAllowed("PLATFORM_OPERATOR") public void save(BillingAdapter billingAdapter) throws ObjectNotFoundException, NonUniqueBusinessKeyException, DuplicateAdapterException { ArgumentValidator.notNull("Billing adapter", billingAdapter); try { if (billingAdapter.getKey() == 0L) { ds.persist(billingAdapter); } else { BillingAdapter ba = ds.getReference(BillingAdapter.class, billingAdapter.getKey()); ba.setBillingIdentifier(billingAdapter.getBillingIdentifier()); ba.setName(billingAdapter.getName()); ba.setDefaultAdapter(billingAdapter.isDefaultAdapter()); ba.setConnectionProperties(billingAdapter .getConnectionProperties()); ds.flush(); } } catch (EJBTransactionRolledbackException e) { if (isEntityExistsException(e)) { throw new DuplicateAdapterException( "Duplicate adapter with unique id " + billingAdapter.getBillingIdentifier()); } else { throw e; } } }
/** * <b>Testcase:</b> Try to insert User without a related Organization<br> * <b>ExpectedResult:</b> PersistenceException * * @throws Throwable */ @Test(expected = EJBTransactionRolledbackException.class) public void testUserWithoutOrganization() throws Throwable { runTX(new Callable<Void>() { @Override public Void call() throws Exception { doTestUserWithoutOrganization(); return null; } }); }
/** * Tries to create a organization/role reference that already exists in the * same constellation. This should end up in an exception. */ @Test public void testCreateOrganizationToRoleDuplicate() throws Exception { final OrganizationRole role = new OrganizationRole(); role.setRoleName(OrganizationRoleType.SUPPLIER); persistDO(role); roles.add(role); doCreateCustomerOrgs(); final OrganizationToRole orgToRole1 = new OrganizationToRole(); orgToRole1.setOrganization(orgs.get(0)); orgToRole1.setOrganizationRole(role); persistDO(orgToRole1); orgToRoles.add(orgToRole1); final OrganizationToRole orgToRole2 = new OrganizationToRole(); orgToRole2.setOrganization(orgs.get(0)); orgToRole2.setOrganizationRole(role); try { persistDO(orgToRole2); Assert.fail("Object must not be stored due to unique constraint violation"); } catch (EJBTransactionRolledbackException e) { // now ensure that the second store operation did not pass OrganizationToRole storedOrgToRole = runTX(new Callable<OrganizationToRole>() { public OrganizationToRole call() throws Exception { return doGetStoredOrgToRoleviaTK(orgToRole2); } }); Assert.assertNull("Transaction has not been rolled back", storedOrgToRole); // also ensure that no history has been created List<?> hist = getHistoryForDO(orgToRole2); Assert.assertEquals( "Transaction rollback did not remove history entries", 0, hist.size()); } orgToRoles.add(orgToRole2); }
/** * <b>Testcase:</b> Try to insert Subscription without a related * Organization<br> * <b>ExpectedResult:</b> PersistenceException * * @throws Throwable */ @Test(expected = EJBTransactionRolledbackException.class) public void testSubscriptionWithoutOrganization() throws Throwable { runTX(new Callable<Void>() { @Override public Void call() throws Exception { doTestSubscriptionWithoutOrganization(); return null; } }); }
/** * <b>Testcase:</b> Try to insert Subscription without a related Product<br> * <b>ExpectedResult:</b> PersistenceException * * @throws Throwable */ @Test(expected = EJBTransactionRolledbackException.class) public void testSubscriptionWithoutProduct() throws Throwable { runTX(new Callable<Void>() { @Override public Void call() throws Exception { doTestSubscriptionWithoutProduct(); return null; } }); }
/** * Update new review to the database * * @param productReview * review need to be updated * @throws ObjectNotFoundException * if the review is not found * @throws ConcurrentModificationException * if the review has been modified concurrently * @throws OperationNotPermittedException * if the caller is not allowed to perform the operation. */ private void updatedReview(ProductReview productReview) throws ObjectNotFoundException, ConcurrentModificationException, OperationNotPermittedException { checkIfAllowedToModify(productReview); try { dm.flush(); } catch (EJBTransactionRolledbackException e) { ConcurrentModificationException cme = new ConcurrentModificationException( productReview.getClass().getSimpleName(), productReview.getVersion()); cme.fillInStackTrace(); throw cme; } }
protected <T> T refreshEntry(T entity) throws DatabaseException{ try { getEntityManager().flush(); getEntityManager().refresh(entity); return entity; } catch (EJBTransactionRolledbackException | HibernateException | PersistenceException e) { throw new DatabaseException("Refresh of entity " + entity.toString() + " failed. " + e.getMessage()); } }
protected <T> T find(String idField, Long id, Class clazz) throws DatabaseException { try { CriteriaBuilder cb = getEntityManager().getCriteriaBuilder(); CriteriaQuery<T> c = cb.createQuery(clazz); Root<T> root = c.from(clazz); CriteriaQuery<T> one = c.select(root).where(cb.equal(root.get(idField), id)); TypedQuery<T> oneQuery = getEntityManager().createQuery(one); return oneQuery.getSingleResult(); } catch (EJBTransactionRolledbackException | PersistenceException e) { throw new DatabaseException("Could not find entity of class " + clazz.toString() + ", " + e.getMessage()); } }
protected <T> List<T> findAll(Class clazz) throws DatabaseException { try { CriteriaBuilder cb = getEntityManager().getCriteriaBuilder(); CriteriaQuery<T> c = cb.createQuery(clazz); Root<T> root = c.from(clazz); CriteriaQuery<T> all = c.select(root); TypedQuery<T> allQuery = getEntityManager().createQuery(all); return allQuery.getResultList(); } catch (EJBTransactionRolledbackException | PersistenceException e) { throw new DatabaseException("Could not find entity of class " + clazz.toString() + ", " + e.getMessage()); } }
/** * Called when a JMS message is received. Extracts control information (Corr.Id..) and attempts to unwrap request * from textmessage * * @param message received JMS message */ public void onMessage(Message message) { if (isValidRequestResponse(message)) { try { process(message); } catch (JMSException | JMSRuntimeException | EJBTransactionRolledbackException jms) { getLogger().error("FATAL: Could not send response! {}", jms.getMessage()); } } }