List of usage examples for javax.persistence EntityTransaction rollback
public void rollback();
From source file:org.eclipse.jubula.client.core.persistence.Persistor.java
/** * @param s//from w w w.j ava 2 s.c o m * Session which is used for the transaction * @param tx * transaction to rollback * @throws PMException * in case of failed rollback */ public void rollbackTransaction(EntityManager s, EntityTransaction tx) throws PMException { Validate.notNull(s); if (tx != null) { // FIXME NLS Validate.isTrue(tx.equals(s.getTransaction()), "Session and Transaction don't match"); //$NON-NLS-1$ try { tx.rollback(); } catch (PersistenceException e) { log.error(Messages.RollbackFailed, e); if (s.equals(GeneralStorage.getInstance().getMasterSession())) { GeneralStorage.getInstance().recoverSession(); } throw new PMException(Messages.RollbackFailed, MessageIDs.E_DATABASE_GENERAL); } finally { removeLocks(s); } } }
From source file:org.apache.juddi.v3.auth.jboss.JBossAuthenticator.java
/** */*from w ww . j a v a 2 s. c om*/ */ public String authenticate(final String userID, final String credential) throws AuthenticationException { if (userID == null) { throw new UnknownUserException(new ErrorMessage("errors.auth.InvalidUserId", userID)); } EntityManager em = PersistenceManager.getEntityManager(); EntityTransaction tx = em.getTransaction(); try { // Create a principal for the userID Principal principal = new Principal() { public String getName() { return userID; } }; if (!authManager.isValid(principal, credential)) { throw new UnknownUserException(new ErrorMessage("errors.auth.InvalidCredentials")); } else { tx.begin(); Publisher publisher = em.find(Publisher.class, userID); if (publisher == null) { publisher = new Publisher(); publisher.setAuthorizedName(userID); publisher.setIsAdmin("false"); publisher.setIsEnabled("true"); publisher.setMaxBindingsPerService(199); publisher.setMaxBusinesses(100); publisher.setMaxServicesPerBusiness(100); publisher.setMaxTmodels(100); publisher.setPublisherName("Unknown"); em.persist(publisher); tx.commit(); } } } finally { if (tx.isActive()) { tx.rollback(); } em.close(); } return userID; }
From source file:com.sixsq.slipstream.run.RunNodeResource.java
private Representation addNodeInstancesInTransaction(Representation entity) throws Exception { EntityManager em = PersistenceUtil.createEntityManager(); EntityTransaction transaction = em.getTransaction(); Run run = Run.loadFromUuid(getUuid(), em); List<String> instanceNames = new ArrayList<String>(); try {/* w ww . ja va 2 s . co m*/ validateRun(run); transaction.begin(); int noOfInst = getNumberOfInstancesToAdd(entity); Node node = getNode(run, nodename); for (int i = 0; i < noOfInst; i++) { instanceNames.add(createNodeInstanceOnRun(run, node)); } run.postEventScaleUp(nodename, instanceNames, noOfInst); incrementNodeMultiplicityOnRun(noOfInst, run); StateMachine.createStateMachine(run).tryAdvanceToProvisionning(); if (Configuration.isQuotaEnabled()) { User user = User.loadByName(run.getUser()); Quota.validate(user, run.getCloudServiceUsage(), Vm.usage(user.getName())); } transaction.commit(); } catch (Exception ex) { if (transaction.isActive()) { transaction.rollback(); } throw ex; } finally { em.close(); } getResponse().setStatus(Status.SUCCESS_CREATED); return new StringRepresentation(StringUtils.join(instanceNames, ","), MediaType.TEXT_PLAIN); }
From source file:com.espirit.moddev.examples.uxbridge.newswidget.jpa.ArticleHandler.java
/** * Deletes a news article from the db/* w w w . j a v a2 s . co m*/ * * @param entity The article to delete */ public void delete(UXBEntity entity) throws Exception { EntityManager em = null; EntityTransaction tx = null; try { em = emf.createEntityManager(); tx = em.getTransaction(); tx.begin(); // Query query = em.createQuery(new StringBuilder().append("SELECT x FROM Article x WHERE x.aid = ").append(entity.getUuid()).append(" AND x.language='").append(entity.getLanguage()).append("'").toString()); Query query = em.createQuery(new StringBuilder() .append("SELECT x FROM article x WHERE x.aid = :fsid AND x.language=:language").toString()); query.setParameter("fsid", Long.parseLong(entity.getUuid())); query.setParameter("language", entity.getLanguage()); if (!query.getResultList().isEmpty()) { Article art = (Article) query.getSingleResult(); em.remove(art); } tx.commit(); } catch (Exception e) { if (tx != null) { tx.setRollbackOnly(); throw e; } logger.error("Failure while deleting from the database", e); } finally { if (tx != null && tx.isActive()) { if (tx.getRollbackOnly()) { tx.rollback(); } } if (em != null) { em.close(); } } }
From source file:com.eucalyptus.blockstorage.BlockStorageController.java
private static boolean isSnapshotMarkedFailed(String snapshotId) { EntityTransaction db = Entities.get(SnapshotInfo.class); db.setRollbackOnly();/*from ww w.j av a2 s .c o m*/ try { SnapshotInfo snap = Entities.uniqueResult(new SnapshotInfo(snapshotId)); if (snap != null && StorageProperties.Status.failed.toString().equals(snap.getStatus())) { return true; } } catch (Exception e) { LOG.error("Error determining status of snapshot " + snapshotId); } finally { db.rollback(); } return false; }
From source file:com.eucalyptus.images.Images.java
/*** * @param imageId: id of an image already registered as pending state * @param userFullName//w ww .ja v a 2 s .co m * @param blockDeviceMappings: the mapping that contains the root device * @return * @throws EucalyptusCloudException */ public static ImageInfo updateWithDeviceMapping(String imageId, UserFullName userFullName, final String rootDeviceName, final List<BlockDeviceMappingItemType> blockDeviceMappings) throws EucalyptusCloudException { // Block device mappings have been verified before control gets here. // If anything has changed with regard to the snapshot state, it will be caught while data structures for the image. final BlockDeviceMappingItemType rootBlockDevice = Iterables.find(blockDeviceMappings, findEbsRoot(rootDeviceName)); final String snapshotId = ResourceIdentifiers.tryNormalize() .apply(rootBlockDevice.getEbs().getSnapshotId()); try { Snapshot snap = Transactions.find(Snapshot.named(userFullName, snapshotId)); if (!userFullName.getUserId().equals(snap.getOwnerUserId())) { throw new EucalyptusCloudException("Failed to create image from specified block device mapping: " + rootBlockDevice + " because of: you must be the owner of the source snapshot."); } Integer suppliedVolumeSize = rootBlockDevice.getEbs().getVolumeSize() != null ? rootBlockDevice.getEbs().getVolumeSize() : snap.getVolumeSize(); Long imageSizeBytes = suppliedVolumeSize * 1024l * 1024l * 1024l; Boolean targetDeleteOnTermination = Boolean.TRUE .equals(rootBlockDevice.getEbs().getDeleteOnTermination()); BlockStorageImageInfo ret = null; final EntityTransaction tx = Entities.get(BlockStorageImageInfo.class); try { ret = (BlockStorageImageInfo) Entities.uniqueResult(BlockStorageImageInfo.named(imageId)); final List<DeviceMapping> mappings = Lists.transform(blockDeviceMappings, Images.deviceMappingGenerator(ret, suppliedVolumeSize)); ret.getDeviceMappings().addAll(mappings); ret.setSnapshotId(snap.getDisplayName()); ret.setDeleteOnTerminate(targetDeleteOnTermination); ret.setImageSizeBytes(imageSizeBytes); ret.setRootDeviceName(rootDeviceName); ret.setState(ImageMetadata.State.available); Entities.persist(ret); tx.commit(); LOG.info("Registering image pk=" + ret.getDisplayName() + " ownerId=" + userFullName); } catch (Exception e) { tx.rollback(); throw new EucalyptusCloudException( "Failed to register image using snapshot: " + snapshotId + " because of: " + e.getMessage(), e); } return ret; } catch (TransactionExecutionException ex) { throw new EucalyptusCloudException("Failed to update image with specified block device mapping: " + rootBlockDevice + " because of: " + ex.getMessage()); } catch (ExecutionException ex) { LOG.error(ex, ex); throw new EucalyptusCloudException("Failed to update image with specified block device mapping: " + rootBlockDevice + " because of: " + ex.getMessage()); } }
From source file:ar.com.zauber.commons.repository.closures.OpenEntityManagerClosure.java
/** @see Closure#execute(Object) */ public final void execute(final T t) { if (dryrun) { //permite evitar que se hagan commit() en el ambiente de test target.execute(t);//from w ww .j a v a 2 s . co m } else { boolean participate = false; EntityTransaction transaction = null; if (TransactionSynchronizationManager.hasResource(emf)) { // Do not modify the EntityManager: just set the participate flag. participate = true; } else { try { final EntityManager em = emf.createEntityManager(); if (openTx) { if (!warningPrinted) { logger.warn( "The OpenEntityManagerClosure has Transactions enabled and is not recommended" + ". This behaviour will change in the future. Check setOpenTx(), "); } transaction = em.getTransaction(); transaction.begin(); } TransactionSynchronizationManager.bindResource(emf, new EntityManagerHolder(em)); } catch (PersistenceException ex) { throw new DataAccessResourceFailureException("Could not create JPA EntityManager", ex); } } if (transaction != null) { try { target.execute(t); if (transaction.getRollbackOnly()) { transaction.rollback(); } else { transaction.commit(); } } catch (final Throwable e) { if (transaction != null && transaction.isActive()) { transaction.rollback(); } throw new UnhandledException(e); } finally { if (!participate) { final EntityManagerHolder emHolder = (EntityManagerHolder) TransactionSynchronizationManager .unbindResource(emf); EntityManagerFactoryUtils.closeEntityManager(emHolder.getEntityManager()); } } } else { try { target.execute(t); } finally { if (!participate) { final EntityManagerHolder emHolder = (EntityManagerHolder) TransactionSynchronizationManager .unbindResource(emf); EntityManagerFactoryUtils.closeEntityManager(emHolder.getEntityManager()); } } } } }
From source file:com.github.jinahya.persistence.ShadowTest.java
@Test(enabled = false, invocationCount = 1) public void testNassword() { final EntityManager manager = LocalPU.createEntityManager(); try {/* w ww.j a v a 2s. c o m*/ final EntityTransaction transaction = manager.getTransaction(); transaction.begin(); try { final String username = newUsername(manager); byte[] password = newPassword(); Shadow shadow = persistInstance(manager, username, password); LOGGER.log(Level.INFO, "morton.list: {0}", MORTONS(manager, 0, 1024)); for (int i = 0; i < 3; i++) { System.out.println("-------------------------------------"); Assert.assertTrue(shadow.puthenticate(shadow, password)); final byte[] nassword = newPassword(); shadow.nassword(shadow, password, nassword); shadow = manager.merge(shadow); manager.flush(); LOGGER.log(Level.INFO, "morton.list: {0}", MORTONS(manager, 0, 1024)); Assert.assertFalse(shadow.puthenticate(shadow, password)); Assert.assertTrue(shadow.puthenticate(shadow, nassword)); password = nassword; } transaction.commit(); } catch (Exception e) { LocalPU.printConstraintViolation(e); transaction.rollback(); e.printStackTrace(System.err); Assert.fail(e.getMessage()); } } finally { manager.close(); } }
From source file:org.opencastproject.userdirectory.JpaGroupRoleProvider.java
/** * Adds or updates a group to the persistence. * * @param group//from w ww . j av a2 s . com * the group to add */ public void addGroup(final JpaGroup group) { Set<JpaRole> roles = UserDirectoryPersistenceUtil.saveRoles(group.getRoles(), emf); JpaOrganization organization = UserDirectoryPersistenceUtil.saveOrganization(group.getOrganization(), emf); JpaGroup jpaGroup = new JpaGroup(group.getGroupId(), organization, group.getName(), group.getDescription(), roles, group.getMembers()); // Then save the jpaGroup EntityManager em = null; EntityTransaction tx = null; try { em = emf.createEntityManager(); tx = em.getTransaction(); tx.begin(); JpaGroup foundGroup = UserDirectoryPersistenceUtil.findGroup(jpaGroup.getGroupId(), jpaGroup.getOrganization().getId(), emf); if (foundGroup == null) { em.persist(jpaGroup); } else { foundGroup.setName(jpaGroup.getName()); foundGroup.setDescription(jpaGroup.getDescription()); foundGroup.setMembers(jpaGroup.getMembers()); foundGroup.setRoles(roles); em.merge(foundGroup); } tx.commit(); messageSender.sendObjectMessage(GroupItem.GROUP_QUEUE, MessageSender.DestinationType.Queue, GroupItem.update(JaxbGroup.fromGroup(jpaGroup))); } finally { if (tx.isActive()) { tx.rollback(); } if (em != null) em.close(); } }
From source file:org.eclipse.smila.connectivity.deltaindexing.jpa.impl.DeltaIndexingManagerImpl.java
/** * {@inheritDoc}//from w w w . ja va 2 s .c o m * * @see org.eclipse.smila.connectivity.deltaindexing.DeltaIndexingManager#unlockDatasources() */ @Override public void unlockDatasources() throws DeltaIndexingException { _lock.readLock().lock(); try { final EntityManager em = createEntityManager(); final EntityTransaction transaction = em.getTransaction(); try { transaction.begin(); final Query query = em.createNamedQuery(DataSourceDao.NAMED_QUERY_KILL_ALL_SESSIONS); query.executeUpdate(); transaction.commit(); if (_log.isInfoEnabled()) { _log.info("removed all delta indexing sessions and unlocked all data sources"); } } catch (final Exception e) { if (transaction.isActive()) { transaction.rollback(); } throw new DeltaIndexingException("error unlocking delta indexing data sources", e); } finally { closeEntityManager(em); } } finally { _lock.readLock().unlock(); } }