Java Code Examples for javax.persistence.EntityTransaction#isActive()

The following examples show how to use javax.persistence.EntityTransaction#isActive() . 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: InfinispanHibernateCacheLocal.java    From infinispan-simple-tutorials with Apache License 2.0 6 votes vote down vote up
private static void persistEntities() {
   try (Session em = createEntityManagerWithStatsCleared()) {
      EntityTransaction tx = em.getTransaction();
      try {
         tx.begin();

         em.persist(new Event("Caught a pokemon!"));
         em.persist(new Event("Hatched an egg"));
         em.persist(new Event("Became a gym leader"));
      } catch (Throwable t) {
         tx.setRollbackOnly();
         throw t;
      } finally {
         if (tx.isActive()) tx.commit();
         else tx.rollback();
      }
   }
}
 
Example 2
Source File: TransactionRunner.java    From james-project with Apache License 2.0 6 votes vote down vote up
public <T> T runAndRetrieveResult(Function<EntityManager, T> toResult,
                                  Function<PersistenceException, T> errorHandler) {
    EntityManager entityManager = entityManagerFactory.createEntityManager();
    EntityTransaction transaction = entityManager.getTransaction();
    try {
        transaction.begin();
        T result = toResult.apply(entityManager);
        transaction.commit();
        return result;
    } catch (PersistenceException e) {
        LOGGER.warn("Could not execute transaction", e);
        if (transaction.isActive()) {
            transaction.rollback();
        }
        return errorHandler.apply(e);
    } finally {
        EntityManagerUtils.safelyClose(entityManager);
    }
}
 
Example 3
Source File: DBAuditDestination.java    From ranger with Apache License 2.0 6 votes vote down vote up
private boolean commitTransaction() {
	boolean ret = false;
	EntityTransaction trx = null;

	try {
		trx = getTransaction();

		if (trx != null && trx.isActive()) {
			trx.commit();
			ret = true;
		} else {
			throw new Exception("trx is null or not active");
		}
	} catch (Throwable excp) {
		logger.error("DBAuditDestination.commitTransaction(): failed", excp);

		cleanUp(); // so that next insert will try to init()
	} finally {
		clearEntityManager();
	}

	return ret;
}
 
Example 4
Source File: JPASubscriptionMapper.java    From james-project with Apache License 2.0 6 votes vote down vote up
@Override
public void delete(Subscription subscription) throws SubscriptionException {
    EntityManager entityManager = getEntityManager();
    EntityTransaction transaction = entityManager.getTransaction();
    boolean localTransaction = !transaction.isActive();
    if (localTransaction) {
        transaction.begin();
    }
    try {
        findJpaSubscription(entityManager, subscription)
            .ifPresent(entityManager::remove);
        if (localTransaction) {
            if (transaction.isActive()) {
                transaction.commit();
            }
        }
    } catch (PersistenceException e) {
        if (transaction.isActive()) {
            transaction.rollback();
        }
        throw new SubscriptionException(e);
    }
}
 
Example 5
Source File: JPAFunctionalityTestEndpoint.java    From quarkus with Apache License 2.0 6 votes vote down vote up
private static void verifyHqlFetch(EntityManagerFactory emf) {
    EntityManager em = emf.createEntityManager();
    try {
        EntityTransaction transaction = em.getTransaction();
        try {
            transaction.begin();

            em.createQuery("from Person p left join fetch p.address a").getResultList();

            transaction.commit();
        } catch (Exception e) {
            if (transaction.isActive()) {
                transaction.rollback();
            }
            throw e;
        }
    } finally {
        em.close();
    }
}
 
Example 6
Source File: InfinispanHibernateCacheLocal.java    From infinispan-simple-tutorials with Apache License 2.0 6 votes vote down vote up
private static void deleteEntity(long id) {
   try (Session em = createEntityManagerWithStatsCleared()) {
      EntityTransaction tx = em.getTransaction();
      try {
         tx.begin();

         Event event = em.find(Event.class, id);
         em.remove(event);
      } catch (Throwable t) {
         tx.setRollbackOnly();
         throw t;
      } finally {
         if (tx.isActive()) tx.commit();
         else tx.rollback();
      }
   }
}
 
Example 7
Source File: LdapSimpleAuthenticator.java    From juddi with Apache License 2.0 6 votes vote down vote up
public UddiEntityPublisher identify(String authInfo, String authorizedName, WebServiceContext ctx) throws AuthenticationException, FatalErrorException {
    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {
        tx.begin();
        Publisher publisher = em.find(Publisher.class, authorizedName);
        if (publisher == null)
            throw new UnknownUserException(new ErrorMessage("errors.auth.NoPublisher", authorizedName));
        return publisher;
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        em.close();
    }
}
 
Example 8
Source File: AbstractTest.java    From hibernate-master-class with Apache License 2.0 6 votes vote down vote up
protected <T> T doInJPA(JPATransactionFunction<T> function) {
    T result = null;
    EntityManager entityManager = null;
    EntityTransaction txn = null;
    try {
        entityManager = emf.createEntityManager();
        function.beforeTransactionCompletion();
        txn = entityManager.getTransaction();
        txn.begin();
        result = function.apply(entityManager);
        txn.commit();
    } catch (RuntimeException e) {
        if ( txn != null && txn.isActive()) txn.rollback();
        throw e;
    } finally {
        function.afterTransactionCompletion();
        if (entityManager != null) {
            entityManager.close();
        }
    }
    return result;
}
 
Example 9
Source File: ModelValidationTest.java    From pnc with Apache License 2.0 6 votes vote down vote up
@Test
public void testProductVersionStringValidationFailureOnCommit() throws Exception {

    ProductVersion productVersion1 = ProductVersion.Builder.newBuilder()
            .product(Product.Builder.newBuilder().id(1).build())
            .version("foo") // Invalid version string
            .build();

    EntityManager em = getEmFactory().createEntityManager();
    EntityTransaction tx1 = em.getTransaction();

    try {
        tx1.begin();
        em.persist(productVersion1);
        tx1.commit(); // This should throw a Rollback exception caused by the constraint violation

    } catch (RollbackException e) {
        if (tx1 != null && tx1.isActive()) {
            tx1.rollback();
        }
        Assert.assertTrue(e.getCause() instanceof ConstraintViolationException);
    } finally {
        em.close();
    }

}
 
Example 10
Source File: SoapboxDao.java    From soapbox-race with GNU General Public License v2.0 5 votes vote down vote up
private void remove(ISoapBoxEntity entity) {
	EntityTransaction tx = null;
	try {
		EntityManager manager = ConnectionDB.getManager();
		tx = manager.getTransaction();
		tx.begin();
		manager.remove(entity);
		tx.commit();
	} catch (Exception e) {
		if (tx != null && tx.isActive()) {
			tx.rollback();
			e.printStackTrace();
		}
	}
}
 
Example 11
Source File: SoapboxDao.java    From soapbox-race with GNU General Public License v2.0 5 votes vote down vote up
private void persist(ISoapBoxEntity entity) {
	EntityTransaction tx = null;
	try {
		EntityManager manager = ConnectionDB.getManager();
		tx = manager.getTransaction();
		tx.begin();
		manager.persist(entity);
		tx.commit();
	} catch (Exception e) {
		if (tx != null && tx.isActive()) {
			tx.rollback();
			e.printStackTrace();
		}
	}
}
 
Example 12
Source File: DbAuditProvider.java    From ranger with Apache License 2.0 5 votes vote down vote up
private boolean beginTransaction() {
	EntityTransaction trx = getTransaction();
	
	if(trx != null && !trx.isActive()) {
		trx.begin();
	}

	if(trx == null) {
		LOG.warn("DbAuditProvider.beginTransaction(): trx is null");
	}
	
	return trx != null;
}
 
Example 13
Source File: UDDIReplicationImpl.java    From juddi with Apache License 2.0 5 votes vote down vote up
private synchronized UDDIReplicationPortType getReplicationClient(String node) {
        if (cache.containsKey(node)) {
                return cache.get(node);
        }
        UDDIService svc = new UDDIService();
        UDDIReplicationPortType replicationClient = svc.getUDDIReplicationPort();
        TransportSecurityHelper.applyTransportSecurity((BindingProvider) replicationClient);

        EntityManager em = PersistenceManager.getEntityManager();
        EntityTransaction tx = em.getTransaction();
        try {
                tx.begin();
                StringBuilder sql = new StringBuilder();
                sql.append("select c from ReplicationConfiguration c order by c.serialNumber desc");
                //sql.toString();
                Query qry = em.createQuery(sql.toString());
                qry.setMaxResults(1);

                org.apache.juddi.model.ReplicationConfiguration resultList = (org.apache.juddi.model.ReplicationConfiguration) qry.getSingleResult();
                for (Operator o : resultList.getOperator()) {
                        if (o.getOperatorNodeID().equalsIgnoreCase(node)) {
                                ((BindingProvider) replicationClient).getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, o.getSoapReplicationURL());
                                cache.put(node, replicationClient);
                                return replicationClient;
                        }
                }
                tx.rollback();

        } catch (Exception ex) {
                logger.fatal("Node not found!" + node, ex);
        } finally {
                if (tx.isActive()) {
                        tx.rollback();
                }
                em.close();
        }
        //em.close();
        return null;

}
 
Example 14
Source File: JPATransactionalMapper.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Override
protected void rollback() throws MailboxException {
    EntityTransaction transaction = entityManager.getTransaction();
    // check if we have a transaction to rollback
    if (transaction.isActive()) {
        getEntityManager().getTransaction().rollback();
    }
}
 
Example 15
Source File: ValidateValueSetValidation.java    From juddi with Apache License 2.0 5 votes vote down vote up
/**
 * return the publisher
 *
 * @param tmodelKey
 * @return
 * @throws ValueNotAllowedException
 */
public static TModel GetTModel_API_IfExists(String tmodelKey) throws ValueNotAllowedException {
        EntityManager em = PersistenceManager.getEntityManager();

        TModel apitmodel = null;
        if (em == null) {
                //this is normally the Install class firing up
                log.warn(new ErrorMessage("errors.tmodel.ReferentialIntegrityNullEM"));
                return null;
        } else {


                EntityTransaction tx = em.getTransaction();
                try {
                        Tmodel modelTModel = null;
                        tx.begin();
                        modelTModel = em.find(org.apache.juddi.model.Tmodel.class, tmodelKey);
                        if (modelTModel != null) {
                                apitmodel = new TModel();
                                try {
                                        MappingModelToApi.mapTModel(modelTModel, apitmodel);
                                } catch (DispositionReportFaultMessage ex) {
                                        log.warn(ex);
                                        apitmodel=null;
                                }


                        }
                        tx.commit();
                } finally {
                        if (tx.isActive()) {
                                tx.rollback();
                        }
                        em.close();
                }

        }
        return apitmodel;
}
 
Example 16
Source File: NewFileInfoDAO.java    From Truck-Factor with MIT License 5 votes vote down vote up
public int filterAndUpdateFilesInfoByLanguage(String whereClauses, String filterStamp){
	String custom = "";
	     
	String hql = "UPDATE  newfileinfo AS fi "
			+ "SET filtered = \'TRUE\', filterinfo = \'"+ filterStamp +"\'  "
			+ "FROM projectinfo AS pi    "
			+ "WHERE pi.fullname = fi.repositoryname AND "
			+ whereClauses
			+ ";";
			
			
	Query q = em.createNativeQuery(hql);
	int rows =0 ;
	EntityTransaction tx = this.em.getTransaction();
	try {
		tx.begin();
		rows = q.executeUpdate();
		tx.commit();
	} catch (RuntimeException e) {
		if(tx != null && tx.isActive()) 
			tx.rollback();
		throw e;
	} 
	finally{
		this.em.clear();
	}
	return rows;
		
}
 
Example 17
Source File: NewFileInfoDAO.java    From Truck-Factor with MIT License 5 votes vote down vote up
public int updateLanguageFileInfo(String projectName, String language, List<String> paths) {
	FileType fileType = FileType.getType(language);
	List<Query> queries = new ArrayList<Query>();
	for (String path : paths) {			
		if (path.contains("\'"))
			path = path.replace("'", "''");
		String hql = "UPDATE  newfileinfo "
				+ "SET kind = \'"
				+ fileType
				+ "\'  , language = \'"
				+ language
				+ "\', filtered = \'FALSE\' "
				+ ", filterinfo = \'\' "
				+ "WHERE repositoryname = \'" + projectName + "\' AND path =  \'"
				+ path + "\' " + ";";
		queries.add(em.createNativeQuery(hql));
	}
	int rows =0 ;
	EntityTransaction tx = this.em.getTransaction();
	try {
		tx.begin();
		for (Query query : queries) {
			rows += query.executeUpdate();
		}			
		tx.commit();
	} catch (RuntimeException e) {
		if(tx != null && tx.isActive()) 
			tx.rollback();
		throw e;
	} 
	finally{
		this.em.clear();
	}
	return rows;
	
}
 
Example 18
Source File: JPAPersistenceManager.java    From Knowage-Server with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public void updateRecord(JSONObject aRecord, RegistryConfiguration registryConf) {

	EntityTransaction entityTransaction = null;

	logger.debug("IN");
	EntityManager entityManager = null;
	try {
		Assert.assertNotNull(aRecord, "Input parameter [record] cannot be null");
		Assert.assertNotNull(aRecord, "Input parameter [registryConf] cannot be null");

		logger.debug("New record: " + aRecord.toString(3));
		logger.debug("Target entity: " + registryConf.getEntity());

		entityManager = dataSource.getEntityManager();
		Assert.assertNotNull(entityManager, "entityManager cannot be null");

		entityTransaction = entityManager.getTransaction();

		EntityType targetEntity = getTargetEntity(registryConf, entityManager);
		String keyAttributeName = getKeyAttributeName(targetEntity);
		logger.debug("Key attribute name is equal to " + keyAttributeName);

		Iterator it = aRecord.keys();

		Object keyColumnValue = aRecord.get(keyAttributeName);
		logger.debug("Key of new record is equal to " + keyColumnValue);
		logger.debug("Key column java type equal to [" + targetEntity.getJavaType() + "]");
		Attribute a = targetEntity.getAttribute(keyAttributeName);
		Object obj = entityManager.find(targetEntity.getJavaType(), this.convertValue(keyColumnValue, a));
		logger.debug("Key column class is equal to [" + obj.getClass().getName() + "]");

		while (it.hasNext()) {
			String attributeName = (String) it.next();
			logger.debug("Processing column [" + attributeName + "] ...");

			if (keyAttributeName.equals(attributeName)) {
				logger.debug("Skip column [" + attributeName + "] because it is the key of the table");
				continue;
			}
			Column column = registryConf.getColumnConfiguration(attributeName);
			if (!column.isEditable()) {
				logger.debug("Skip column [" + attributeName + "] because it is not editable");
				continue;
			}
			List columnDepends = new ArrayList();
			if (column.getDependences() != null && !"".equals(column.getDependences())) {
				String[] dependences = column.getDependences().split(",");
				for (int i = 0; i < dependences.length; i++) {
					// get dependences informations
					Column dependenceColumns = getDependenceColumns(registryConf.getColumns(), dependences[i]);
					if (dependenceColumns != null)
						columnDepends.add(dependenceColumns);
				}
			}

			// if column is info column do not update
			if (!column.isInfoColumn()) {
				if (column.getSubEntity() != null) {
					logger.debug("Column [" + attributeName + "] is a foreign key");
					manageForeignKey(targetEntity, column, obj, attributeName, aRecord, columnDepends, entityManager, registryConf.getColumns());
				} else {
					logger.debug("Column [" + attributeName + "] is a normal column");
					manageProperty(targetEntity, obj, attributeName, aRecord);
				}
			}
		}

		if (!entityTransaction.isActive()) {
			entityTransaction.begin();
		}

		entityManager.persist(obj);
		entityManager.flush();
		entityTransaction.commit();

	} catch (Throwable t) {
		if (entityTransaction != null && entityTransaction.isActive()) {
			entityTransaction.rollback();
		}
		logger.error(t);
		throw new SpagoBIRuntimeException("Error saving entity", t);
	} finally {
		if (entityManager != null) {
			if (entityManager.isOpen()) {
				entityManager.close();
			}
		}
		logger.debug("OUT");
	}

}
 
Example 19
Source File: JPADomainList.java    From james-project with Apache License 2.0 4 votes vote down vote up
private void rollback(EntityTransaction transaction) {
    if (transaction.isActive()) {
        transaction.rollback();
    }
}
 
Example 20
Source File: MCRURNGranularRESTService.java    From mycore with GNU General Public License v3.0 4 votes vote down vote up
private MCRDNBURN registerURN(MCRDerivate deriv, String filePath) throws MCRPersistentIdentifierException {
    MCRObjectID derivID = deriv.getId();

    Function<String, Integer> countCreatedPI = s -> MCRPIManager
        .getInstance()
        .getCreatedIdentifiers(derivID, getType(), getServiceID())
        .size();

    int seed = Optional.of(filePath)
        .filter(p -> !"".equals(p))
        .map(countCreatedPI)
        .map(count -> count + 1)
        .orElse(1);

    MCRDNBURN derivURN = Optional
        .ofNullable(deriv.getDerivate())
        .map(MCRObjectDerivate::getURN)
        .flatMap(new MCRDNBURNParser()::parse)
        .orElseGet(() -> createNewURN(deriv));

    String setID = derivID.getNumberAsString();
    GranularURNGenerator granularURNGen = new GranularURNGenerator(seed, derivURN, setID);
    Function<MCRPath, Supplier<String>> generateURN = p -> granularURNGen.getURNSupplier();

    LinkedHashMap<Supplier<String>, MCRPath> urnPathMap = derivateFileStream.apply(deriv)
        .filter(notInIgnoreList().and(matchFile(filePath)))
        .sorted()
        .collect(Collectors.toMap(generateURN, p -> p, (m1, m2) -> m1,
            LinkedHashMap::new));

    if (!"".equals(filePath) && urnPathMap.isEmpty()) {
        String errMsg = new MessageFormat("File {0} does not exist in {1}.\n", Locale.ROOT)
            .format(new Object[] { filePath, derivID.toString() })
            + "Use absolute path of file without owner ID like /abs/path/to/file.\n";

        throw new MCRPersistentIdentifierException(errMsg);
    }

    urnPathMap.forEach(createFileMetadata(deriv).andThen(persistURN(deriv)));

    try {
        MCRMetadataManager.update(deriv);
    } catch (MCRPersistenceException | MCRAccessException e) {
        LOGGER.error("Error while updating derivate {}", derivID, e);
    }

    EntityTransaction transaction = MCREntityManagerProvider
        .getCurrentEntityManager()
        .getTransaction();

    if (!transaction.isActive()) {
        transaction.begin();
    }

    transaction.commit();

    return derivURN;
}