List of usage examples for javax.persistence EntityManager flush
public void flush();
From source file:com.webbfontaine.valuewebb.timer.RatesUpdater.java
@Asynchronous @Transactional/*from w w w.j av a 2 s.c om*/ public QuartzTriggerHandle scheduleTask(@Expiration Date when, @IntervalCron String interval) { HashMap<String, BigDecimal> ratesFromBank = ratesFromBank(); if (ratesFromBank.isEmpty()) { LOGGER.error("No rates passed to update, check web site and source code!"); return null; } EntityManager entityManager = Utils.getEntityManager(); List<Rate> existingRates = entityManager.createQuery("from Rate r where r.eov is null").getResultList(); Transaction tx = ((org.jboss.seam.persistence.HibernateSessionProxy) entityManager.getDelegate()) .getTransaction(); try { tx.begin(); for (Rate existingRecord : existingRates) { BigDecimal latestRateForCurrency = ratesFromBank.get(existingRecord.getCod()); if (latestRateForCurrency == null) { LOGGER.warn("Currency code '{0}' exists but absent in updates", existingRecord.getCod()); continue; } if (existingRecord.getExch().doubleValue() != latestRateForCurrency.doubleValue()) { //i get double value because bigdecimal can return 0.2240 which is not equal to 0.224 when comparing BD values /* close existing rate and open new one from today */ Date tomorrowDate = Utils.getTomorrowDate(); existingRecord.setEov(tomorrowDate); // since scheduler works at 21:00 Rate newRecord = new Rate(null, existingRecord.getCod(), 1, latestRateForCurrency, tomorrowDate, null); entityManager.persist(existingRecord); entityManager.persist(newRecord); LOGGER.info("Updated Exchange rate for {0}, old: {1}, new: {2}", newRecord.getCod(), existingRecord.unitRate(), newRecord.unitRate()); } } entityManager.flush(); tx.commit(); } catch (Exception e) { LOGGER.error("Exception on updating rates", e); if (tx != null) { tx.rollback(); } } return null; }
From source file:BO.UserHandler.java
public boolean addFriend(VUser u) { EntityManager em; EntityManagerFactory emf;/*from ww w.j a v a2s . co m*/ emf = Persistence.createEntityManagerFactory(PERSISTENCE_NAME); em = emf.createEntityManager(); try { em.getTransaction().begin(); System.out.println(u.getEmail()); System.out.println(u.getFriendToAdd()); try { List<Friendship> f = (List<Friendship>) em .createQuery("SELECT f from Friendship f WHERE f.receivingFriend.email LIKE :email1 " + "AND f.sendingFriend.email LIKE :email2") .setParameter("email1", u.getEmail()).setParameter("email2", u.getFriendToAdd()) .getResultList(); if (!f.isEmpty()) { return false; } } catch (Exception e) { } try { List<Friendship> f = (List<Friendship>) em .createQuery("SELECT f from Friendship f WHERE f.sendingFriend.email LIKE :email1 " + "AND f.receivingFriend.email LIKE :email2") .setParameter("email1", u.getEmail()).setParameter("email2", u.getFriendToAdd()) .getResultList(); if (!f.isEmpty()) { return false; } } catch (Exception e) { } User sender = getUserByEmail(u.getEmail()); User receiver = getUserByEmail(u.getFriendToAdd()); Friendship friendship = new Friendship(sender, receiver); em.persist(friendship); em.flush(); em.getTransaction().commit(); return true; } catch (Exception e) { return false; } finally { if (em != null) { em.close(); } emf.close(); } }
From source file:cn.buk.hotel.dao.HotelDaoImpl.java
@Override @Transactional/*from ww w . jav a2s .c o m*/ public synchronized int createHotelRatePlan(HotelRatePlan hotelRatePlan) { int retCode = 0; List<HotelRatePlan> ratePlans = null; EntityManager em = getEm(); logger.debug(Thread.currentThread().getName() + ", createHotelRatePlan[" + hotelRatePlan.getHotelInfo().getHotelCode() + "] begin: "); try { ratePlans = em.createQuery( "select o from HotelRatePlan o where o.ratePlanCode = :ratePlanCode and o.hotelInfo = :hotelInfo") .setParameter("ratePlanCode", hotelRatePlan.getRatePlanCode()) .setParameter("hotelInfo", hotelRatePlan.getHotelInfo()).getResultList(); if (ratePlans.size() > 0) { retCode = 2; HotelRatePlan plan0 = ratePlans.get(0); //booking rule List<HotelRatePlanBookingRule> rules0 = em .createQuery("select o from HotelRatePlanBookingRule o where o.hotelRatePlan = :plan") .setParameter("plan", plan0).getResultList(); for (HotelRatePlanBookingRule rule0 : rules0) { em.remove(rule0); em.flush(); } if (hotelRatePlan.getHotelRatePlanBookingRules() != null) { for (HotelRatePlanBookingRule rule : hotelRatePlan.getHotelRatePlanBookingRules()) { rule.setHotelRatePlan(plan0); em.persist(rule); } } //offer List<HotelRatePlanOffer> offers0 = em .createQuery("select o from HotelRatePlanOffer o where o.hotelRatePlan = :plan") .setParameter("plan", plan0).getResultList(); for (HotelRatePlanOffer offer0 : offers0) { em.remove(offer0); em.flush(); } if (hotelRatePlan.getHotelRatePlanOffers() != null) { for (HotelRatePlanOffer offer : hotelRatePlan.getHotelRatePlanOffers()) { offer.setHotelRatePlan(plan0); em.persist(offer); } } //rate List<HotelRatePlanRate> rates0 = em.createQuery( "select o from HotelRatePlanRate o where o.hotelRatePlan = :plan order by o.startDate") .setParameter("plan", plan0).getResultList(); for (HotelRatePlanRate rate0 : rates0) { for (HotelRatePlanRate rate : hotelRatePlan.getHotelRatePlanRates()) { if (rate0.getStartDate().getTime() == rate.getStartDate().getTime()) { em.remove(rate0); em.flush(); break; } } } for (HotelRatePlanRate rate : hotelRatePlan.getHotelRatePlanRates()) { rate.setHotelRatePlan(plan0); em.persist(rate); } logger.debug(Thread.currentThread().getName() + ", createHotelRatePlan[" + hotelRatePlan.getHotelInfo().getHotelCode() + "] updated. "); } else { em.persist(hotelRatePlan); retCode = 1; logger.debug(Thread.currentThread().getName() + ", createHotelRatePlan[" + hotelRatePlan.getHotelInfo().getHotelCode() + "] created. "); } } catch (Exception ex) { ex.printStackTrace(); retCode = -1; logger.error(Thread.currentThread().getName() + ", createHotelRatePlan[" + hotelRatePlan.getHotelInfo().getHotelCode() + "]: " + ex.getMessage()); } getEm().detach(hotelRatePlan); if (ratePlans != null) { for (HotelRatePlan ratePlan : ratePlans) { getEm().detach(ratePlan); } } logger.debug(Thread.currentThread().getName() + ", createHotelRatePlan[" + hotelRatePlan.getHotelInfo().getHotelCode() + "] end. "); return retCode; }
From source file:nl.b3p.kaartenbalie.struts.UserAction.java
@Override public ActionForward delete(ActionMapping mapping, DynaValidatorForm dynaForm, HttpServletRequest request, HttpServletResponse response) throws Exception { log.debug("Getting entity manager ......"); EntityManager em = getEntityManager(); if (!isTokenValid(request)) { prepareMethod(dynaForm, request, EDIT, LIST); addAlternateMessage(mapping, request, TOKEN_ERROR_KEY); return getAlternateForward(mapping, request); }/*from w w w . j av a 2s . c om*/ User user = getUser(dynaForm, request, false); if (user == null) { prepareMethod(dynaForm, request, LIST, EDIT); addAlternateMessage(mapping, request, NOTFOUND_ERROR_KEY); return getAlternateForward(mapping, request); } User sessionUser = (User) request.getUserPrincipal(); if (sessionUser.getId().equals(user.getId())) { prepareMethod(dynaForm, request, LIST, EDIT); addAlternateMessage(mapping, request, DELETE_ADMIN_ERROR_KEY); return getAlternateForward(mapping, request); } /* * Als je een gebruiker probeert te verwijderen waarvan de main organization * null is geeft hij een fout. Wellicht als in het verleden handmatig een * aanpassing is gedaan in de database. Tijdelijk even op de beheerder org zetten * waarna de gebruiker gewist kan worden. * * TODO: Nagaan op welke plekken die main org null zou kunnen worden. */ if (user.getMainOrganization() == null) { user.setMainOrganization(sessionUser.getMainOrganization()); em.merge(user); em.flush(); } em.remove(user); em.flush(); dynaForm.initialize(mapping); prepareMethod(dynaForm, request, LIST, EDIT); addDefaultMessage(mapping, request, ACKNOWLEDGE_MESSAGES); return getDefaultForward(mapping, request); }
From source file:net.echinopsii.ariane.community.plugin.rabbitmq.directory.RabbitmqDirectoryBootstrap.java
private void plugDirectoryJPAProvider() { Company pivotal = null;/*from w w w. j a va2 s. c o m*/ Application rabbitmq = null; directoryJpaProvider.addSubPersistenceBundle(FrameworkUtil.getBundle(RabbitmqDirectoryBootstrap.class)); EntityManager em = directoryJpaProvider.createEM(); CriteriaBuilder builder = em.getCriteriaBuilder(); CriteriaQuery<Company> cmpCriteria = builder.createQuery(Company.class); Root<Company> cmpRoot = cmpCriteria.from(Company.class); cmpCriteria.select(cmpRoot).where(builder.equal(cmpRoot.<String>get("name"), "Pivotal")); TypedQuery<Company> cmpQuery = em.createQuery(cmpCriteria); try { pivotal = cmpQuery.getSingleResult(); log.debug("Pivotal company already defined ..."); } catch (NoResultException e) { log.debug("Pivotal company will be defined ..."); } catch (Exception e) { throw e; } CriteriaQuery<Application> appCriteria = builder.createQuery(Application.class); Root<Application> appRoot = appCriteria.from(Application.class); appCriteria.select(appRoot).where(builder.equal(appRoot.<String>get("name"), "RabbitMQ")); TypedQuery<Application> appQuery = em.createQuery(appCriteria); try { rabbitmq = appQuery.getSingleResult(); log.debug("RabbitMQ application already defined ..."); } catch (NoResultException e) { log.debug("RabbitMQ application will be defined ..."); } catch (Exception e) { throw e; } em.getTransaction().begin(); if (pivotal == null) { pivotal = new Company().setNameR("Pivotal").setDescriptionR("Pivotal"); em.persist(pivotal); } if (rabbitmq == null) { rabbitmq = new Application().setNameR("RabbitMQ").setCompanyR(pivotal).setShortNameR("RabbitMQ") .setColorCodeR("ff6600").setDescriptionR("Robust messaging for applications"); em.persist(rabbitmq); } if (!pivotal.getApplications().contains(rabbitmq)) { pivotal.getApplications().add(rabbitmq); } em.flush(); em.getTransaction().commit(); }
From source file:org.mule.module.jpa.command.Query.java
public Object execute(EntityManager entityManager, Object payload, Map<String, Object> parameters, Boolean flush) throws Exception { Object queryParameters = parameters.get("queryParameters"); Object result;// w w w .ja v a2 s. com if (queryParameters instanceof CriteriaQuery) { logger.debug("Executing CriteriaQuery: " + queryParameters); result = entityManager.createQuery((CriteriaQuery) queryParameters).getResultList(); } else if (parameters.containsKey("namedQuery")) { logger.debug("Executing Named Query: " + parameters.get("namedQuery")); javax.persistence.Query query = entityManager.createNamedQuery((String) parameters.get("namedQuery")); if (queryParameters != null) { setParameters(queryParameters, query); } result = query.getResultList(); } else if (parameters.containsKey("statement")) { logger.debug("Executing JPQL statement: " + parameters.get("statement")); javax.persistence.Query query = entityManager.createQuery((String) parameters.get("statement")); if (queryParameters != null) { setParameters(queryParameters, query); } result = query.getResultList(); } else { throw new JPAException( "Couldn't resolve query from either the query parameters or the statement attribute"); } if (flush) { entityManager.flush(); } return result; }
From source file:BO.UserHandler.java
public int sendChallengeRequest(VUser user) { EntityManager em; EntityManagerFactory emf;/* w ww. java2 s. c o m*/ emf = Persistence.createEntityManagerFactory(PERSISTENCE_NAME); em = emf.createEntityManager(); try { em.getTransaction().begin(); System.out.println("Challenged by: " + user.getEmail()); System.out.println("Challenged friend: " + user.getFriendToAdd()); User friend = getUserByEmail(user.getFriendToAdd()); GameServerCommunicator gameComm = new GameServerCommunicator(); ArrayList<String> playerNames = new ArrayList<>(); playerNames.add(user.getEmail()); playerNames.add(user.getFriendToAdd()); int gameId = gameComm.requestNewGame(playerNames); if (gameId == -1) { //if something went wrong return -1; } //Send cloud message to friend JSONObject notificationObj = new JSONObject(); notificationObj.put("body", "CHALLENGE " + user.getEmail() + " " + GameInfo.getInstance().getIp() + " " + GameInfo.getInstance().getClientPort() + " " + gameId); notificationObj.put("title", "A Challenge"); JSONObject messageObj = new JSONObject(); messageObj.put("token", friend.getDeviceToken()); messageObj.put("notification", notificationObj); JSONObject mainObject = new JSONObject(); mainObject.put("message", messageObj); HttpPost url = getHttpURL(); url.setEntity(new StringEntity(mainObject.toString())); HttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(url); System.out.println("Response:"); HttpEntity entity = response.getEntity(); String responseString = EntityUtils.toString(entity, "UTF-8"); System.out.println(responseString); em.flush(); em.getTransaction().commit(); return gameId; } catch (Exception e) { System.out.println(e); return -1; } finally { if (em != null) { em.close(); } emf.close(); } }
From source file:nl.b3p.kaartenbalie.core.server.accounting.AccountManager.java
/** * /*from w w w .ja va2 s. c o m*/ * @param accountTransaction * @param user * @throws java.lang.Exception */ public synchronized void commitTransaction(Transaction accountTransaction, User user) throws Exception { if (!enableAccounting) { return; } if (accountTransaction != null) { //Create an EntityManager log.debug("Getting entity manager ......"); EntityManager em = MyEMFDatabase.getEntityManager(MyEMFDatabase.MAIN_EM); //Get the account and set the current balance. Update the class variable at the same time. Account account = (Account) em.find(Account.class, organizationId); balance = account.getCreditBalance(); //Set the account & user for the accountTransaction. accountTransaction.setAccount(account); accountTransaction.setUser(user); try { //Run validation (checks what type of transaction is allowed..) accountTransaction.validate(); //Now check if the transaction either has to deposit or withdraw... BigDecimal newBalance = null; if (accountTransaction.getType() == Transaction.DEPOSIT) { newBalance = balance.add(accountTransaction.getCreditAlteration()); } else if (accountTransaction.getType() == Transaction.WITHDRAW) { newBalance = balance.subtract(accountTransaction.getCreditAlteration()); if (newBalance.doubleValue() < 0) { throw new TransactionDeniedException("Insufficient credits for transaction. " + "Required credits: " + accountTransaction.getCreditAlteration().setScale(2, BigDecimal.ROUND_HALF_UP) .toString() + ", " + "Current balance: " + balance.setScale(2, BigDecimal.ROUND_HALF_UP).toString()); } } else { log.error("Unsupported transaction type"); throw new Exception("Unsupported transaction type"); } account.setCreditBalance(newBalance); accountTransaction.setMutationDate(new Date()); accountTransaction.setStatus(Transaction.ACCEPTED); Iterator iterPriceComp = accountTransaction.getLayerPriceCompositions().iterator(); while (iterPriceComp.hasNext()) { LayerPriceComposition lpc = (LayerPriceComposition) iterPriceComp.next(); em.persist(lpc); } em.merge(accountTransaction); em.flush(); balance = newBalance; } catch (TransactionDeniedException tde) { accountTransaction.setErrorMessage(tde.getMessage()); accountTransaction.setStatus(Transaction.REFUSED); em.merge(accountTransaction); em.flush(); throw tde; } } }
From source file:org.sparkcommerce.openadmin.server.service.persistence.module.provider.RuleFieldPersistenceProvider.java
protected boolean populateQuantityBaseRuleCollection(EntityManager em, DataDTOToMVELTranslator translator, String entityKey, String fieldService, String jsonPropertyValue, Collection<QuantityBasedRule> criteriaList, Class<?> memberType) { boolean dirty = false; if (!StringUtils.isEmpty(jsonPropertyValue)) { DataWrapper dw = ruleFieldExtractionUtility.convertJsonToDataWrapper(jsonPropertyValue); if (dw != null && StringUtils.isEmpty(dw.getError())) { List<QuantityBasedRule> updatedRules = new ArrayList<QuantityBasedRule>(); for (DataDTO dto : dw.getData()) { if (dto.getId() != null && !CollectionUtils.isEmpty(criteriaList)) { checkId: {/*from w w w . j ava 2s.c om*/ //updates are comprehensive, even data that was not changed //is submitted here //Update Existing Criteria for (QuantityBasedRule quantityBasedRule : criteriaList) { //make compatible with enterprise module Long sandBoxVersionId = sandBoxHelper.getSandBoxVersionId(em, quantityBasedRule.getClass(), dto.getId()); if (sandBoxVersionId == null) { sandBoxVersionId = dto.getId(); } if (sandBoxVersionId.equals(quantityBasedRule.getId())) { //don't update if the data has not changed if (!quantityBasedRule.getQuantity().equals(dto.getQuantity())) { quantityBasedRule.setQuantity(dto.getQuantity()); dirty = true; } try { String mvel = ruleFieldExtractionUtility.convertDTOToMvelString(translator, entityKey, dto, fieldService); if (!quantityBasedRule.getMatchRule().equals(mvel)) { quantityBasedRule.setMatchRule(mvel); dirty = true; } } catch (MVELTranslationException e) { throw new RuntimeException(e); } //make compatible with enterprise module em.flush(); updatedRules.add(quantityBasedRule); break checkId; } } throw new IllegalArgumentException("Unable to update the rule of type (" + memberType.getName() + ") because an update was requested for id (" + dto.getId() + "), which does not exist."); } } else { //Create a new Criteria QuantityBasedRule quantityBasedRule; try { quantityBasedRule = (QuantityBasedRule) memberType.newInstance(); quantityBasedRule.setQuantity(dto.getQuantity()); quantityBasedRule.setMatchRule(ruleFieldExtractionUtility .convertDTOToMvelString(translator, entityKey, dto, fieldService)); if (StringUtils.isEmpty(quantityBasedRule.getMatchRule()) && !StringUtils.isEmpty(dw.getRawMvel())) { quantityBasedRule.setMatchRule(dw.getRawMvel()); } } catch (Exception e) { throw new RuntimeException(e); } sandBoxHelper.setupSandBoxState(quantityBasedRule, em); em.persist(quantityBasedRule); criteriaList.add(quantityBasedRule); updatedRules.add(quantityBasedRule); dirty = true; } } //if an item was not included in the comprehensive submit from the client, we can assume that the //listing was deleted, so we remove it here. Iterator<QuantityBasedRule> itr = criteriaList.iterator(); while (itr.hasNext()) { checkForRemove: { QuantityBasedRule original = itr.next(); for (QuantityBasedRule quantityBasedRule : updatedRules) { if (String.valueOf(original.getId()) .equals(String.valueOf(quantityBasedRule.getId()))) { break checkForRemove; } } sandBoxHelper.archiveObject(original, em); itr.remove(); dirty = true; } } } } return dirty; }
From source file:org.eclipse.jubula.client.core.persistence.ProjectPM.java
/** * delete a project/*from w w w .j a v a 2 s.com*/ * * @param proj * project to delete * @param isActProject * flag to label the actual project * @throws PMAlreadyLockedException * if project is already locked in db * @throws PMDirtyVersionException * if project to delete is modified in the meantime * @throws JBException * if a session cannot closed * @throws PMExtProjDeletedException * if a project (but not the current) was deleted by another * user * @throws ProjectDeletedException * if the current project was deleted by another user * @throws InterruptedException * if the operation was canceled */ public static void deleteProject(IProjectPO proj, boolean isActProject) throws PMDirtyVersionException, PMAlreadyLockedException, PMExtProjDeletedException, ProjectDeletedException, JBException, InterruptedException { Validate.notNull(proj, "Project to delete is null"); //$NON-NLS-1$ EntityManager deleteSess = null; IProjectPO p = null; final Long projId = proj.getId(); try { if (isActProject) { EntityManager s = GeneralStorage.getInstance().getMasterSession(); IProjectPO currProj = s.find(NodeMaker.getProjectPOClass(), projId, LockModeType.READ); if (currProj == null) { throw new ProjectDeletedException(Messages.ProjectWasDeleted, MessageIDs.E_CURRENT_PROJ_DEL); } } } catch (PersistenceException e) { handleDBExceptionForMasterSession(proj, e); } try { deleteSess = Persistor.instance().openSession(); EntityTransaction tx = Persistor.instance().getTransaction(deleteSess); p = deleteSess.find(NodeMaker.getProjectPOClass(), projId); if (p == null) { if (isActProject) { throw new ProjectDeletedException("Current Project was deleted", //$NON-NLS-1$ MessageIDs.E_CURRENT_PROJ_DEL); } throw new PMExtProjDeletedException(Messages.ProjectWasDeleted + StringConstants.DOT, MessageIDs.E_DELETED_OBJECT); } Persistor.instance().lockPO(deleteSess, p); deleteProjectIndependentDBObjects(deleteSess, p); // FIXME zeb Workaround for EclipseLink deleting the objects in the // wrong order. Test Cases that reference Test Data Cubes // were being deleted *after* the Test Data Cubes // themselves. List<ISpecPersistable> specObjList = new ArrayList<ISpecPersistable>( p.getSpecObjCont().getSpecObjList()); List<IExecPersistable> execObjList = new ArrayList<IExecPersistable>( p.getExecObjCont().getExecObjList()); for (ISpecPersistable po : specObjList) { PersistenceUtil.removeChildNodes(po, deleteSess); p.getSpecObjCont().removeSpecObject(po); Persistor.instance().deletePO(deleteSess, po); } for (IExecPersistable po : execObjList) { PersistenceUtil.removeChildNodes(po, deleteSess); p.getExecObjCont().removeExecObject(po); Persistor.instance().deletePO(deleteSess, po); } deleteSess.flush(); // FIXME zeb end workaround Persistor.instance().deletePO(deleteSess, p); CompNamePM.deleteCompNames(deleteSess, projId); Persistor.instance().commitTransaction(deleteSess, tx); tx = null; } catch (PersistenceException e) { handleDBExceptionForAnySession(p, e, deleteSess); } finally { Persistor.instance().dropSession(deleteSess); } ProjectNameBP.getInstance().checkAndDeleteName(proj.getGuid()); }