List of usage examples for javax.persistence EntityTransaction getRollbackOnly
public boolean getRollbackOnly();
From source file:com.espirit.moddev.examples.uxbridge.newswidget.jpa.ArticleHandler.java
/** * Deletes a news article from the db//from w ww.jav a 2s. c o 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: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);// w ww . j a v a2s. 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.espirit.moddev.examples.uxbridge.newswidget.jpa.ArticleHandler.java
/** * Add or update a news article in the db * * @param entity The NewsItem// w w w . java 2s .com */ public void add(UXBEntity entity) throws Exception { Article art = buildArticle(entity); 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 = :fsid AND x.language=:language").toString()); query.setParameter("fsid", art.getAid()); query.setParameter("language", art.getLanguage()); /* * If the item exists in the db, we update the content and the title of the existing item */ if (query.getResultList().size() > 0) { Article db = (Article) query.getSingleResult(); db.setContent(art.getContent()); db.setTitle(art.getTitle()); db.setUrl(art.getUrl()); db.setCreated(art.getCreated()); db.setAid(art.getAid()); db.setLanguage(art.getLanguage()); db.setVersion(art.getVersion()); db.setLastmodified(art.getLastmodified()); art = db; } // save to db em.persist(art); em.flush(); tx.commit(); } catch (Exception e) { if (tx != null) { tx.setRollbackOnly(); throw e; } logger.error("Failure while writing to the database", e); } finally { if (tx != null && tx.isActive()) { if (tx.getRollbackOnly()) { tx.rollback(); } } if (em != null) { em.close(); } } }
From source file:com.espirit.moddev.examples.uxbridge.newsdrilldown.jpa.NewsHandler.java
/** * handle the update and save process.//from w w w.jav a 2s . c om * * @param entity the newsdrilldown entity * @throws Exception the exception */ private void handle(UXBEntity entity) throws Exception { /** * Due to a hibernate problem when updating or saving a newsdrilldown with * related categories we have to perform these step for saving the newsdrilldown * * 1. save/update all categories and remove them from the newsdrilldown * 1.1 save/update all metaCategories and remove them from the categories * 1.2 save the categories * 1.3 read all metaCategories to the categories * 1.4 save the categories again to create the relations * 2. save the newsdrilldown * 3. read all categories to the newsdrilldown */ EntityManager em = null; EntityTransaction tx = null; try { News news = buildNews(entity); List<Long> categories = new ArrayList<Long>(); /* * 1. update or save all categories * Steps 1.1 - 1.4 */ if (news.getCategories() != null && !news.getCategories().isEmpty()) { for (NewsCategory cat : news.getCategories()) { cat = saveNewsCategory(cat); if (!categories.contains(cat.getFs_id())) { categories.add(cat.getFs_id()); } } news.setCategories(new ArrayList<NewsCategory>()); } em = emf.createEntityManager(); tx = em.getTransaction(); tx.begin(); // 2. save the newsdrilldown news = saveNews(news, em); // 3. read all categories to the newsdrilldown if (!categories.isEmpty()) { for (Long cat : categories) { NewsCategory ncat = getNewsCategory(cat, news.getLanguage(), em); news.getCategories().add(ncat); } } tx.commit(); } catch (Exception e) { if (tx != null && tx.isActive()) { tx.setRollbackOnly(); } throw e; } finally { if (tx != null && tx.isActive()) { if (tx.getRollbackOnly()) { tx.rollback(); } } if (em != null) { em.close(); } } }
From source file:com.espirit.moddev.examples.uxbridge.newsdrilldown.jpa.NewsHandler.java
/** * saves or updates a newscategory./*from w ww.jav a 2s.com*/ * * @param category the category * @return the category with the new id * @throws Exception the exception */ private NewsCategory saveNewsCategory(NewsCategory category) throws Exception { EntityManager em = null; EntityTransaction tx = null; try { em = emf.createEntityManager(); tx = em.getTransaction(); tx.begin(); // try loading the category for the firstspirit id NewsCategory cat = getNewsCategory(category.getFs_id(), category.getLanguage(), em); if (cat != null) { List<NewsMetaCategory> metaCats = category.getMetaCategories(); // the already persistent categories List<NewsMetaCategory> original_metaCats = cat.getMetaCategories(); // update existing category cat.setMetaCategories(new ArrayList<NewsMetaCategory>()); for (NewsMetaCategory metaCat : metaCats) { metaCat = saveNewsMetaCategory(metaCat, em); cat.getMetaCategories().add(metaCat); original_metaCats.remove(metaCat); } for (NewsMetaCategory mc : original_metaCats) { mc.setLastmodified(category.getLastmodified()); } cat.getMetaCategories().addAll(original_metaCats); cat.setFs_id(category.getFs_id()); cat.setLanguage(category.getLanguage()); cat.setName(category.getName()); cat.setVersion(category.getVersion()); cat.setLastmodified(category.getLastmodified()); // update category = em.merge(cat); } else { updateMetaCategories(category, em); // save to db em.persist(category); } tx.commit(); return category; } catch (Exception e) { if (tx != null && tx.isActive()) { tx.setRollbackOnly(); } logger.error("", e); throw e; } finally { if (tx != null && tx.isActive()) { if (tx.getRollbackOnly()) { tx.rollback(); } } if (em != null) { em.close(); } } }
From source file:com.espirit.moddev.examples.uxbridge.newsdrilldown.jpa.NewsHandler.java
/** * Deletes every item older than the creationTime of the UXBEntity. * * @param entity Entity containing the expireDate (= createTime of the entity) *///from w w w. j av a 2 s . c om public void cleanup(UXBEntity entity) throws Exception { EntityManager em = null; EntityTransaction tx = null; try { em = emf.createEntityManager(); tx = em.getTransaction(); tx.begin(); // Remove old newsdrilldown Query query = em.createQuery(new StringBuilder() .append("SELECT x FROM news x WHERE x.lastmodified<:expiredate ").toString()); query.setParameter("expiredate", entity.getCreateTime()); if (!query.getResultList().isEmpty()) { for (Object obj : query.getResultList()) { News art = (News) obj; em.remove(art); } } // Remove old newsCategories query = em.createQuery(new StringBuilder() .append("SELECT x FROM category x WHERE x.lastmodified<:expiredate ").toString()); query.setParameter("expiredate", entity.getCreateTime()); if (!query.getResultList().isEmpty()) { for (Object obj : query.getResultList()) { NewsCategory art = (NewsCategory) obj; em.remove(art); } } // Remove old newsMetaCategories query = em.createQuery(new StringBuilder() .append("SELECT x FROM metaCategory x WHERE x.lastmodified<:expiredate ").toString()); query.setParameter("expiredate", entity.getCreateTime()); if (!query.getResultList().isEmpty()) { for (Object obj : query.getResultList()) { NewsMetaCategory art = (NewsMetaCategory) obj; em.remove(art); } } tx.commit(); } catch (Exception e) { if (tx != null && tx.isActive()) { tx.setRollbackOnly(); } logger.error("Failure while deleting from the database", e); throw e; } finally { if (tx != null && tx.isActive()) { if (tx.getRollbackOnly()) { tx.rollback(); } } if (em != null) { em.close(); } } }
From source file:com.espirit.moddev.examples.uxbridge.newsdrilldown.jpa.NewsHandler.java
/** * Deletes a newsdrilldown from the db.//from w w w. j ava 2s. com * * @param entity The newsdrilldown 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("FROM news x WHERE x.fs_id = :fs_id AND x.language = :language").toString()); query.setParameter("fs_id", Long.parseLong(entity.getUuid())); query.setParameter("language", entity.getLanguage()); if (!query.getResultList().isEmpty()) { News art = (News) query.getSingleResult(); // delete file from filesystem URL url = new URL(art.getUrl()); File file = new File(webpath + url.getPath()); if (file.exists()) { // Try acquiring the lock without blocking. This method returns // null or throws an exception if the file is already locked. try { FileChannel channel = new RandomAccessFile(file, "rw").getChannel(); // Try to lock the file FileLock lock = channel.tryLock(); // Delete the file file.delete(); // Release the lock lock.release(); lock.channel().close(); } catch (OverlappingFileLockException e) { logger.info("File is already locked in this thread or virtual machine"); } catch (MalformedURLException e) { logger.info("wrong url", e); } } // remove article from content repository em.remove(art); } tx.commit(); } catch (Exception e) { if (tx != null) { tx.setRollbackOnly(); } throw e; } finally { if (tx != null && tx.isActive()) { if (tx.getRollbackOnly()) { tx.rollback(); } } if (em != null) { em.close(); } } }
From source file:nl.b3p.kaartenbalie.service.SecurityRealm.java
/** Checks wether an user, given his username and password, is allowed to use the system. * * @param username String representing the username. * @param password String representing the password. * * @return a principal object containing the user if he has been found as a registered user. Otherwise this object wil be empty (null). *///from www . j av a2s . c o m @Override public Principal authenticate(String username, String password) { String encpw = null; try { encpw = KBCrypter.encryptText(password); } catch (Exception ex) { log.error("error encrypting password: ", ex); } Object identity = null; EntityTransaction tx = null; try { identity = MyEMFDatabase.createEntityManager(MyEMFDatabase.REALM_EM); EntityManager em = MyEMFDatabase.getEntityManager(MyEMFDatabase.REALM_EM); tx = em.getTransaction(); tx.begin(); try { User user = (User) em .createQuery("from User u where " + "u.timeout > :nu " + "and lower(u.username) = lower(:username) " + "and u.password = :password") .setParameter("nu", new Date()).setParameter("username", username) .setParameter("password", encpw).getSingleResult(); // if we get a result, this means successful login // set lastloginstatus to null to indicate success user.setLastLoginStatus(null); return user; } catch (NoResultException nre) { log.debug("No results using encrypted password"); } // if login not succesful, set userstate to LOGIN_STATE_WRONG_PASSW User wrong_password_user = (User) em .createQuery( "from User u where " + "u.timeout > :nu " + "and lower(u.username) = lower(:username) ") .setParameter("nu", new Date()).setParameter("username", username).getSingleResult(); wrong_password_user.setLastLoginStatus(User.LOGIN_STATE_WRONG_PASSW_OR_ACCOUNT_EXPIRED); em.flush(); log.warn("Login failure for username " + username); } catch (Exception e) { log.error("Exception checking user credentails", e); if (tx != null && tx.isActive()) { tx.rollback(); } } finally { if (tx != null && tx.isActive() && !tx.getRollbackOnly()) { tx.commit(); } MyEMFDatabase.closeEntityManager(identity, MyEMFDatabase.REALM_EM); } return null; }
From source file:nl.b3p.kaartenbalie.service.SecurityRealm.java
@Override public Principal getAuthenticatedPrincipal(String username, String password) { Object identity = null;/*from w ww . j ava 2s.c o m*/ EntityTransaction tx = null; try { identity = MyEMFDatabase.createEntityManager(MyEMFDatabase.REALM_EM); EntityManager em = MyEMFDatabase.getEntityManager(MyEMFDatabase.REALM_EM); tx = em.getTransaction(); tx.begin(); try { User user = (User) em.createQuery("from User u where " + "lower(u.username) = lower(:username) ") .setParameter("username", username).getSingleResult(); return user; } catch (NoResultException nre) { return null; } } catch (Exception e) { log.error("Exception getting authenticated user from database", e); if (tx != null && tx.isActive()) { tx.rollback(); } } finally { if (tx != null && tx.isActive() && !tx.getRollbackOnly()) { tx.commit(); } MyEMFDatabase.closeEntityManager(identity, MyEMFDatabase.REALM_EM); } return null; }
From source file:nl.b3p.kaartenbalie.service.servlet.CallWMSServlet.java
/** Processes the incoming request and calls the various methods to create the right output stream. * * @param request servlet request//ww w . j av a 2 s . c o m * @param response servlet response * * @throws ServletException * @throws IOException */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { long startTime = System.currentTimeMillis(); StringBuffer baseUrl = createBaseUrl(request, true); if (CAPABILITIES_DTD == null) { CAPABILITIES_DTD = baseUrl.toString() + "/dtd/capabilities_1_1_1.dtd"; } if (EXCEPTION_DTD == null) { EXCEPTION_DTD = baseUrl.toString() + "/dtd/exception_1_1_1.dtd"; } if (DESCRIBELAYER_DTD == null) { DESCRIBELAYER_DTD = baseUrl.toString() + "/dtd/WMS_DescribeLayerResponse.dtd"; } DataWrapper data = new DataWrapper(request, response); Object identity = null; EntityManager em; EntityTransaction tx = null; try { identity = MyEMFDatabase.createEntityManager(MyEMFDatabase.MAIN_EM); em = MyEMFDatabase.getEntityManager(MyEMFDatabase.MAIN_EM); tx = em.getTransaction(); tx.begin(); DataMonitoring rr = new DataMonitoring(); data.setRequestReporting(rr); String serviceName = OGCConstants.WMS_SERVICE_WMS; try { OGCRequest ogcrequest = calcOGCRequest(request); String personalCode = null; if (ogcrequest != null) personalCode = ogcrequest.getPersonalCode(); data.setOgcrequest(ogcrequest); String serviceParam = ogcrequest.getParameter(OGCConstants.SERVICE); if (serviceParam != null || !"".equals(serviceParam)) { serviceName = serviceParam; } String iUrl = ogcrequest.getUrl(); rr.startClientRequest(iUrl, iUrl.getBytes().length, startTime, request.getRemoteAddr(), request.getMethod()); User user = checkLogin(request, personalCode, em); ogcrequest.checkRequestURL(); Organization mainOrg = null; String userName = null; if (user != null) { mainOrg = user.getMainOrganization(); userName = user.getUsername(); } rr.setUserAndOrganization(user, mainOrg); data.setHeader("X-Kaartenbalie-User", userName); parseRequestAndData(data, user); } catch (AccessDeniedException adex) { rr.setClientRequestException(adex); response.addHeader("WWW-Authenticate", "Basic realm=\"Kaartenbalie login\""); response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Access denied to Kaartenbalie"); } catch (ProviderException pex) { log.error("Error while communicating with provider: " + pex.getLocalizedMessage()); rr.setClientRequestException(pex); handleRequestException(pex, data); } catch (Exception e) { log.error(String.format("Error while handling request for URI %s, query string %s: %s: %s", request.getRequestURI(), request.getQueryString(), e.getClass().getName(), e.getMessage()), e); rr.setClientRequestException(e); handleRequestException(e, data); } finally { rr.endClientRequest(serviceName, data.getOperation(), data.getContentLength(), System.currentTimeMillis() - startTime); } if (!tx.getRollbackOnly()) { tx.commit(); } } catch (Exception ex) { log.error("Error creating EntityManager", ex); handleRequestException(ex, data); } finally { if (tx != null && tx.isActive()) { tx.rollback(); } MyEMFDatabase.closeEntityManager(identity, MyEMFDatabase.MAIN_EM); } }