org.hibernate.StaleStateException Java Examples

The following examples show how to use org.hibernate.StaleStateException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: UserService.java    From computoser with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * http://jaspan.com/improved_persistent_login_cookie_best_practice
 */
@Transactional(rollbackFor=StaleStateException.class)
public User rememberMeLogin(String token, String series) {
    User existingLogin = userDao.getLoginFromAuthToken(token, series);
    if (existingLogin == null) {
        User loginBySeries = userDao.getByPropertyValue(User.class, "loginSeries", series);
        // if a login series exists, assume the previous token was stolen, so deleting all persistent logins.
        // An exception is a request made within a few seconds from the last login time
        // which may mean request from the same browser that is not yet aware of the renewed cookie
        if (loginBySeries != null && new Period(loginBySeries.getLastLoginTime(), new DateTime()).getSeconds() < 5) {
            logger.info("Assuming login cookies theft; deleting all sessions for user " + loginBySeries);
            loginBySeries.setLoginSeries(null);
            loginBySeries.setLoginToken(null);
            userDao.persist(loginBySeries);
        } else if (logger.isDebugEnabled()) {
            logger.debug("No existing login found for token=" + token + ", series=" + series);
        }
        return null;
    }
    if (logger.isDebugEnabled()) {
        logger.debug("Existing login found for token=" + token + " and series=" + series);
    }
    fillUserWithNewTokens(existingLogin, series);
    return existingLogin;
}
 
Example #2
Source File: VersionTest.java    From high-performance-java-persistence with Apache License 2.0 6 votes vote down vote up
@Test
public void testOptimisticLockingException() {
    try {
        doInJPA(entityManager -> {
            Product product = entityManager.find(Product.class, 1L);

            executeSync(() -> doInJPA(_entityManager -> {
                LOGGER.info("Batch processor updates product stock");

                Product _product = _entityManager.find(Product.class, 1L);
                _product.setQuantity(0);
            }));

            LOGGER.info("Changing the previously loaded Product entity");
            product.setQuantity(4);
        });
    } catch (Exception expected) {
        LOGGER.error("Throws", expected);

        assertEquals(OptimisticLockException.class, expected.getCause().getClass());
        assertTrue(ExceptionUtil.rootCause(expected) instanceof StaleStateException);
    }
}
 
Example #3
Source File: Expectations.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
private void checkBatched(int rowCount, int batchPosition) {
	if ( rowCount == -2 ) {
		if ( log.isDebugEnabled() ) {
			log.debug( "success of batch update unknown: " + batchPosition );
		}
	}
	else if ( rowCount == -3 ) {
		throw new BatchFailedException( "Batch update failed: " + batchPosition );
	}
	else {
		if ( expectedRowCount > rowCount ) {
			throw new StaleStateException(
					"Batch update returned unexpected row count from update [" + batchPosition +
					"]; actual row count: " + rowCount +
					"; expected: " + expectedRowCount
			);
		}
		if ( expectedRowCount < rowCount ) {
			String msg = "Batch update returned unexpected row count from update [" +
			             batchPosition + "]; actual row count: " + rowCount +
			             "; expected: " + expectedRowCount;
			throw new BatchedTooManyRowsAffectedException( msg, expectedRowCount, rowCount, batchPosition );
		}
	}
}
 
Example #4
Source File: Expectations.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private void checkBatched(int rowCount, int batchPosition) {
	if ( rowCount == -2 ) {
		LOG.debugf( "Success of batch update unknown: %s", batchPosition );
	}
	else if ( rowCount == -3 ) {
		throw new BatchFailedException( "Batch update failed: " + batchPosition );
	}
	else {
		if ( expectedRowCount > rowCount ) {
			throw new StaleStateException(
					"Batch update returned unexpected row count from update ["
							+ batchPosition + "]; actual row count: " + rowCount
							+ "; expected: " + expectedRowCount
			);
		}
		if ( expectedRowCount < rowCount ) {
			String msg = "Batch update returned unexpected row count from update [" +
					batchPosition + "]; actual row count: " + rowCount +
					"; expected: " + expectedRowCount;
			throw new BatchedTooManyRowsAffectedException( msg, expectedRowCount, rowCount, batchPosition );
		}
	}
}
 
Example #5
Source File: IDGenerator.java    From uflo with Apache License 2.0 6 votes vote down vote up
public synchronized long nextId() {
	if (lastId < nextId) {
		for (int attempts = maxAttempts; (attempts > 0); attempts--) {
			try {
				AcquireDbidCommand command = new AcquireDbidCommand(blockSize);
				nextId = commandService.executeCommandInNewTransaction(command);
				lastId = nextId + blockSize - 1;
				break;
			} catch (StaleStateException e) {
				attempts--;
				if (attempts == 0) {
					throw new IllegalStateException("couldn't acquire block of ids, tried "+ maxAttempts + " times");
				}
				// if there are still attempts left, first wait a bit
				int millis = 20 + random.nextInt(200);
				log.debug("optimistic locking failure while trying to acquire id block.  retrying in "+ millis + " millis");
				try {
					Thread.sleep(millis);
				} catch (InterruptedException e1) {
					log.debug("waiting after id block locking failure got interrupted");
				}
			}
		}
	}
	return nextId++;
}
 
Example #6
Source File: HibernateExceptionUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void whenDeletingADeletedObject_thenOptimisticLockException() {
    thrown.expect(isA(OptimisticLockException.class));
    thrown.expectMessage(
        "Batch update returned unexpected row count from update");
    thrown.expectCause(isA(StaleStateException.class));

    Session session = null;
    Transaction transaction = null;

    try {
        session = sessionFactory.openSession();
        transaction = session.beginTransaction();

        Product product1 = new Product();
        product1.setId(12);
        product1.setName("Product 12");
        session.save(product1);
        transaction.commit();
        session.close();

        session = sessionFactory.openSession();
        transaction = session.beginTransaction();
        Product product2 = session.get(Product.class, 12);
        session.createNativeQuery("delete from Product where id=12")
            .executeUpdate();
        // We need to refresh to fix the error.
        // session.refresh(product2);
        session.delete(product2);
        transaction.commit();
    } catch (Exception e) {
        rollbackTransactionQuietly(transaction);
        throw (e);
    } finally {
        closeSessionQuietly(session);
    }
}
 
Example #7
Source File: Expectations.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void checkNonBatched(int rowCount) {
	if ( expectedRowCount > rowCount ) {
		throw new StaleStateException(
				"Unexpected row count: " + rowCount + "; expected: " + expectedRowCount
		);
	}
	if ( expectedRowCount < rowCount ) {
		String msg = "Unexpected row count: " + rowCount + "; expected: " + expectedRowCount;
		throw new TooManyRowsAffectedException( msg, expectedRowCount, rowCount );
	}
}
 
Example #8
Source File: Expectations.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private void checkNonBatched(int rowCount) {
	if ( expectedRowCount > rowCount ) {
		throw new StaleStateException(
				"Unexpected row count: " + rowCount + "; expected: " + expectedRowCount
		);
	}
	if ( expectedRowCount < rowCount ) {
		String msg = "Unexpected row count: " + rowCount + "; expected: " + expectedRowCount;
		throw new TooManyRowsAffectedException( msg, expectedRowCount, rowCount );
	}
}
 
Example #9
Source File: ResilientCartRepositoryImpl.java    From yes-cart with Apache License 2.0 5 votes vote down vote up
private Runnable createRunnable(final ShoppingCart shoppingCart, final String sccCode, final Long sccId) {
    return () -> {

        if (sccCode != null) {
            ShopCodeContext.setShopCode(sccCode);
            ShopCodeContext.setShopId(sccId);
        }

        try {

            // Update process potentially can merge the cart with other stored states (e.g. when user logs in)
            cartUpdateProcessor.updateShoppingCart(shoppingCart);
            // So we re-save it in cache
            putToCache(shoppingCart.getGuid(), shoppingCart);

        } catch (ConcurrencyFailureException cexp) {

            LOG.warn("Unable to persist cart state for {}, caused by concurrency update", shoppingCart.getGuid());

        } catch (StaleStateException sexp) {

            LOG.warn("Unable to persist cart state for {}, caused by stale state", shoppingCart.getGuid());

        } catch (Exception exp) {

            LOG.error("Unable to persist cart state for " + shoppingCart.getGuid(), exp);

        } finally {
            if (sccCode != null) {
                ShopCodeContext.clear();
            }
        }

    };
}
 
Example #10
Source File: HibernateOptimisticLockingFailureException.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
public HibernateOptimisticLockingFailureException(StaleStateException ex) {
	super(ex.getMessage(), ex);
}
 
Example #11
Source File: HibernateOptimisticLockingFailureException.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
public HibernateOptimisticLockingFailureException(StaleStateException ex) {
	super(ex.getMessage(), ex);
}
 
Example #12
Source File: HibernateOptimisticLockingFailureException.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
public HibernateOptimisticLockingFailureException(StaleStateException ex) {
	super(ex.getMessage(), ex);
}
 
Example #13
Source File: HibernateOptimisticLockingFailureException.java    From spring-analysis-note with MIT License 4 votes vote down vote up
public HibernateOptimisticLockingFailureException(StaleStateException ex) {
	super(ex.getMessage(), ex);
}
 
Example #14
Source File: HibernateOptimisticLockingFailureException.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
public HibernateOptimisticLockingFailureException(StaleStateException ex) {
	super(ex.getMessage(), ex);
}
 
Example #15
Source File: HibernateOptimisticLockingFailureException.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
public HibernateOptimisticLockingFailureException(StaleStateException ex) {
	super(ex.getMessage(), ex);
}
 
Example #16
Source File: HibernateOptimisticLockingFailureException.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
public HibernateOptimisticLockingFailureException(StaleStateException ex) {
	super(ex.getMessage(), ex);
}
 
Example #17
Source File: CoreModule.java    From onedev with MIT License 4 votes vote down vote up
private void configureWeb() {
	bind(WicketServlet.class).to(DefaultWicketServlet.class);
	bind(WicketFilter.class).to(DefaultWicketFilter.class);
	bind(WebSocketPolicy.class).toProvider(WebSocketPolicyProvider.class);
	bind(EditSupportRegistry.class).to(DefaultEditSupportRegistry.class);
	bind(WebSocketManager.class).to(DefaultWebSocketManager.class);

	bind(AttachmentUploadServlet.class);
	
	contributeFromPackage(EditSupport.class, EditSupport.class);
	
	bind(WebApplication.class).to(OneWebApplication.class);
	bind(Application.class).to(OneWebApplication.class);
	bind(AvatarManager.class).to(DefaultAvatarManager.class);
	bind(WebSocketManager.class).to(DefaultWebSocketManager.class);
	
	contributeFromPackage(EditSupport.class, EditSupportLocator.class);
	
	contribute(WebApplicationConfigurator.class, new WebApplicationConfigurator() {
		
		@Override
		public void configure(WebApplication application) {
			application.mount(new OnePageMapper("/test", TestPage.class));
		}
		
	});
	
	bind(CommitIndexedBroadcaster.class);
	
	contributeFromPackage(DiffRenderer.class, DiffRenderer.class);
	contributeFromPackage(BlobRendererContribution.class, BlobRendererContribution.class);

	contribute(Extension.class, new EmojiExtension());
	contribute(Extension.class, new SourcePositionTrackExtension());
	
	contributeFromPackage(MarkdownProcessor.class, MarkdownProcessor.class);

	contribute(ResourcePackScopeContribution.class, new ResourcePackScopeContribution() {
		
		@Override
		public Collection<Class<?>> getResourcePackScopes() {
			return Lists.newArrayList(OneWebApplication.class);
		}
		
	});
	contribute(ExpectedExceptionContribution.class, new ExpectedExceptionContribution() {
		
		@SuppressWarnings("unchecked")
		@Override
		public Collection<Class<? extends Exception>> getExpectedExceptionClasses() {
			return Sets.newHashSet(ConstraintViolationException.class, EntityNotFoundException.class, 
					ObjectNotFoundException.class, StaleStateException.class, UnauthorizedException.class, 
					OneException.class, PageExpiredException.class, StalePageException.class);
		}
		
	});

	bind(UrlManager.class).to(DefaultUrlManager.class);
	bind(CodeCommentEventBroadcaster.class);
	bind(PullRequestEventBroadcaster.class);
	bind(IssueEventBroadcaster.class);
	bind(BuildEventBroadcaster.class);
	
	bind(TaskButton.TaskFutureManager.class);
	
	bind(UICustomization.class).toInstance(new UICustomization() {
		
		@Override
		public Class<? extends BasePage> getHomePage() {
			return DashboardPage.class;
		}
		
		@Override
		public List<MainTab> getMainTabs() {
			return Lists.newArrayList(
					new ProjectListTab(), new IssueListTab(), 
					new PullRequestListTab(), new BuildListTab());
		}

	});
}
 
Example #18
Source File: HibernateOptimisticLockingFailureException.java    From java-technology-stack with MIT License 4 votes vote down vote up
public HibernateOptimisticLockingFailureException(StaleStateException ex) {
	super(ex.getMessage(), ex);
}