List of usage examples for org.hibernate Session enableFilter
Filter enableFilter(String filterName);
From source file:ca.qc.cegepoutaouais.tge.pige.server.LoanTermVerificatorTask.java
License:Open Source License
@Override public void run() { Boolean enabled = Boolean.parseBoolean(Configurations.getProperties() .getProperty(ServerConfigs.LOAN_TERM_VERIFICATOR_ENABLED, Boolean.FALSE.toString())); if (!enabled) { logger.info("Le vrificateur d'chance des emprunts est " + "dsactiv. Pour le ractiver, changez la valeur de la " + "ligne 'server.loan_verificator.enabled' 'true' dans " + "le fichier de configurations et redmarrez le serveur ou " + "bien ractiver-le partir du menu 'Gestion' dans PIGE. " + "(ne ncessite pas de redmarrage)."); return;/* w w w .j a v a 2s . c om*/ } logger.info("Dmarrage de la vrification des chances des emprunts..."); Transaction tx = null; List<User> users = null; Session session = null; try { session = PigeHibernateUtil.openSession(); tx = session.beginTransaction(); // Activer le filtre permettant d'exclure les demandes d'emprunt // qui ne sont ni acceptes, ni en retard. Ce filtre est appliqu // la jointure qui permet de rcuprer les demandes d'emprunt // associ au compte. Filter filter = session.enableFilter(Loan.STATUS_FILTER_2PARAM); filter.setParameter(Loan.STATUS_FILTER_PARAM1, LoanStatus.STATUS_LENT); filter.setParameter(Loan.STATUS_FILTER_PARAM2, LoanStatus.STATUS_LATE); // Construire et excuter la requte permettant de rcuprer les // comptes. Une jointure externe permet de rcuprer les demandes // d'emprunt du compte immdiatement dans la mme requte SQL. Criteria crit = session.createCriteria(User.class).setFetchMode(User.LOAN_COLLECTION_REF, FetchMode.JOIN); users = (List) crit.list(); if (users == null) { users = new ArrayList(); } Set userSet = new HashSet(users); Set loans; User user; Loan loan; // Construire une date et heure prdfinie afin de servir de // comparaison pour les chances. Calendar today = Calendar.getInstance(); today.setTime(new Date()); today.set(Calendar.MILLISECOND, 0); today.set(Calendar.SECOND, 0); today.set(Calendar.MINUTE, 0); today.set(Calendar.HOUR, 0); // Date et heure pour l'chance. Calendar term = Calendar.getInstance(); // Itrer dans chaque usager contenant des emprunts en retard... for (Iterator<User> itr = userSet.iterator(); itr.hasNext();) { user = itr.next(); loans = user.getLoans(); boolean hasLate = false; int lateLoanCount = 0; StringBuffer lateLoansDesc = new StringBuffer("<ul>"); // Itrer dans chacun des emprunts en retard de l'usager... for (Iterator<Loan> itr2 = loans.iterator(); itr2.hasNext();) { loan = itr2.next(); // L'heure exacte laquelle un emprunt devient en retard. // 18h00 1 milliseconde. term.setTime(loan.getTerm()); // Rcuprer la date. term.set(Calendar.MILLISECOND, 1); term.set(Calendar.SECOND, 0); term.set(Calendar.MINUTE, 0); term.set(Calendar.HOUR, 18); if (today.after(term)) { logger.debug("Emprunts en retard pour " + user.toString() + ":"); logger.debug(" Today = " + today.getTime().toString()); logger.debug(" Term = " + term.getTime().toString()); // Changer l'tat de l'emprunt. loan.setStatus(LoanStatus.STATUS_LATE); hasLate = true; lateLoanCount++; lateLoansDesc.append( "<li>Qt: " + loan.getQuantity() + ", Desc: " + loan.getDescription() + "</li>"); } } lateLoansDesc.append("</ul><br/><br/>"); if (hasLate) { // Geler le compte de l'utilisateur et indiquer un message // de retard. user.setStatus(UserStatus.STATUS_FROZEN); user.setServerMessage(MessageFormat.format(msgToUser, lateLoanCount)); // Crer un envoi de courriel. Il sera envoy la fin de la // vrification avec les autres retards. EmailService email = new EmailService(); email.setRecipient(user.getEmail()); email.setSubjet( Configurations.getProperties().getProperty("msg.user.email.loan_lateness.subject")); email.setBody(MessageFormat.format( Configurations.getProperties().getProperty("msg.user.email.loan_lateness.body"), lateLoanCount, lateLoansDesc.toString()), true); email.addToBatch(); logger.info("Le compte suivant a t gel cause qu'il " + "contient des emprunts en retard: " + user.asString()); } } // Confirmer les changements la base de donnes. tx.commit(); sendNotifications(today); } catch (Exception hex) { logger.error(hex); if (tx != null) { tx.rollback(); } } finally { if (session != null) { session.close(); } } logger.info("Vrification termine!"); }
From source file:com.abiquo.server.core.common.persistence.JPAConfiguration.java
License:Open Source License
public static EntityManager enableNotTemporalFilters(final EntityManager em) { if (!em.isOpen()) { throw new IllegalStateException("EntityManager must be open"); }/* w ww . j av a2s. com*/ Session session = (Session) em.getDelegate(); for (String filter : ONLY_TEMPORAL_FILTERS) { session.disableFilter(filter); } for (String filter : NOT_TEMPORAL_FILTERS) { session.enableFilter(filter); } return em; }
From source file:com.abiquo.server.core.common.persistence.JPAConfiguration.java
License:Open Source License
public static EntityManager enableOnlyTemporalFilters(final EntityManager em) { if (!em.isOpen()) { throw new IllegalStateException("EntityManager must be open"); }/* ww w . ja v a 2 s.c om*/ Session session = (Session) em.getDelegate(); for (String filter : NOT_TEMPORAL_FILTERS) { session.disableFilter(filter); } for (String filter : ONLY_TEMPORAL_FILTERS) { session.enableFilter(filter); } return em; }
From source file:com.devnexus.ting.repository.jpa.ScheduleItemRepositoryImpl.java
License:Apache License
/** {@inheritDoc} */ @Override// w w w. j a v a 2s . c o m public List<ScheduleItem> getScheduleForEvent(Long eventId) { final Session session = (Session) this.entityManager.getDelegate(); Filter filter = session.enableFilter("userFilter"); if (!(SecurityContextHolder.getContext().getAuthentication() instanceof AnonymousAuthenticationToken)) { final User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); filter.setParameter("userId", user.getId()); } else { filter.setParameter("userId", -1L); } return this.entityManager .createQuery("select si from ScheduleItem si " + "where si.event.id = :eventId " + "order by si.fromTime ASC, si.room.roomOrder ASC", ScheduleItem.class) .setParameter("eventId", eventId).getResultList(); }
From source file:com.devnexus.ting.repository.jpa.SpeakerRepositoryImpl.java
License:Apache License
@SuppressWarnings("unchecked") @Override//from w ww. j a v a2s. c om public List<Speaker> getSpeakersForCurrentEvent() { final Session session = (Session) this.entityManager.getDelegate(); session.enableFilter("presentationFilter"); final List<Speaker> speakers = (List<Speaker>) session .createQuery("select s from Speaker s " + " join fetch s.events e " + " left outer join fetch s.picture " + " where e.current = :iscurrent " + " order by s.lastName ASC, s.firstName ASC") .setParameter("iscurrent", Boolean.TRUE).setCacheable(true).list(); return speakers; }
From source file:com.devnexus.ting.repository.jpa.SpeakerRepositoryImpl.java
License:Apache License
/** * https://hibernate.onjira.com/browse/HHH-6902 *///from w w w .j a v a 2s.c o m @SuppressWarnings("unchecked") @Override public List<Speaker> getSpeakersForEvent(Long eventId) { final Session session = (Session) this.entityManager.getDelegate(); Filter filter = session.enableFilter("presentationFilterEventId"); filter.setParameter("eventId", eventId); final List<Speaker> speakers = (List<Speaker>) this.entityManager .createQuery( "select s from Speaker s " + " join s.events e " + " left outer join fetch s.picture " + "where e.id = :eventId " + "order by s.lastName ASC") .setParameter("eventId", eventId).getResultList(); return speakers; }
From source file:com.devnexus.ting.repository.jpa.SpeakerRepositoryImpl.java
License:Apache License
@Override public Speaker getSpeakerFilteredForEvent(Long speakerId, Event event) { final Session session = (Session) this.entityManager.getDelegate(); Filter filter = session.enableFilter("presentationFilterEventId"); filter.setParameter("eventId", event.getId()); final Speaker speaker = this.entityManager .createQuery("select s from Speaker s left outer join fetch s.picture where s.id = :id", Speaker.class) .setParameter("id", speakerId).getSingleResult(); return speaker; }
From source file:com.ketayao.learn.hibernate.test.cascade.ManyToOneWithFormulaTest.java
License:LGPL
@Test public void testManyToOneFromPk2() throws Exception { Session s1 = HibernateUtil.getSessionFactory().getCurrentSession(); s1.beginTransaction();/*w w w. j av a 2 s . co m*/ s1.enableFilter("getACompany"); Person person = (Person) s1.get(Person.class, 1); List<Company> companies = person.getCompanies(); for (Company company : companies) { System.out.println(company.getQ()); } //s1.save(person); s1.getTransaction().commit(); }
From source file:com.lp.server.angebotstkl.fastlanereader.AgstklpositionHandler.java
License:Open Source License
public Session setFilter(Session session) { session = super.setFilter(session); session.enableFilter("filterMandant").setParameter("paramMandant", theClientDto.getMandant()); return session; }
From source file:com.lp.server.artikel.ejbfac.ArtikelFacBean.java
License:Open Source License
@TransactionAttribute(TransactionAttributeType.NEVER) public byte[] getXLSForPreispflege(Integer artikelgruppeIId, Integer artikelklasseIId, String artikelNrVon, String artikelNrBis, boolean bMitVersteckten, TheClientDto theClientDto) { ByteArrayOutputStream os = new ByteArrayOutputStream(); WritableWorkbook workbook = null;/*from w w w . j ava 2 s .c o m*/ try { workbook = Workbook.createWorkbook(os); } catch (IOException e) { throw new EJBExceptionLP(EJBExceptionLP.FEHLER, e); } try { WritableSheet sheet = workbook.createSheet("Artikel", 0); Session session = FLRSessionFactory.getFactory().openSession(); session.enableFilter("filterMandant").setParameter("paramMandant", theClientDto.getMandant()); session.enableFilter("filterLocale").setParameter("paramLocale", Helper.locale2String(theClientDto.getLocUi())); String queryString = "SELECT artikelliste FROM FLRArtikelliste AS artikelliste WHERE artikelliste.mandant_c_nr='" + theClientDto.getMandant() + "' AND artikelliste.artikelart_c_nr<>'" + ArtikelFac.ARTIKELART_HANDARTIKEL + "'"; if (bMitVersteckten == false) { queryString += " AND artikelliste.b_versteckt=0 "; } if (artikelNrVon != null) { queryString += " AND artikelliste.c_nr >='" + artikelNrVon + "'"; } if (artikelNrBis != null) { String artikelNrBis_Gefuellt = Helper.fitString2Length(artikelNrBis, 25, '_'); queryString += " AND artikelliste.c_nr <='" + artikelNrBis_Gefuellt + "'"; } if (artikelklasseIId != null) { queryString += " AND klasse.i_id=" + artikelklasseIId.intValue(); } if (artikelgruppeIId != null) { queryString += " AND gruppe.i_id=" + artikelgruppeIId.intValue(); } queryString += " ORDER BY artikelliste.c_nr ASC"; org.hibernate.Query query = session.createQuery(queryString); List<?> resultList = query.list(); Iterator<?> resultListIterator = resultList.iterator(); // 1. Zeile = Ueberschrift VkpfartikelpreislisteDto[] vkpfartikelpreislisteDtos = null; try { vkpfartikelpreislisteDtos = getVkPreisfindungFac() .getAlleAktivenPreislisten(Helper.boolean2Short(true), theClientDto); } catch (RemoteException e) { throwEJBExceptionLPRespectOld(e); } // Datumsformat DateFormat customDateFormat = new DateFormat("dd.MM.yyyy"); WritableCellFormat dateFormat = new WritableCellFormat(customDateFormat); // Zahlenformat int iNachkommastellenPreis = getMandantFac().getNachkommastellenPreisVK(theClientDto.getMandant()); NumberFormat customNumberFormatRabatt = new NumberFormat("####0.00"); WritableCellFormat numberFormatRabatt = new WritableCellFormat(customNumberFormatRabatt); String sNachkomma = ""; for (int i = 0; i < iNachkommastellenPreis; i++) { sNachkomma += "0"; } NumberFormat customNumberFormatPreis = new NumberFormat("#######0." + sNachkomma); WritableCellFormat numberFormatPreis = new WritableCellFormat(customNumberFormatPreis); WritableCellFormat numberAsTextFormat = new WritableCellFormat(NumberFormats.TEXT); sheet.addCell(new Label(0, 1, "Artikelnummer")); sheet.addCell(new Label(1, 1, "Bezeichnung")); sheet.addCell(new Label(2, 1, "Zusatzbezeichnung")); sheet.addCell(new Label(3, 1, "Einheit")); sheet.addCell(new Label(4, 1, "Lieferant")); sheet.addCell(new Label(5, 1, "Einzelpreis")); sheet.addCell(new Label(6, 1, "Rabatt")); sheet.addCell(new Label(7, 1, "Nettopreis")); sheet.addCell(new Label(8, 1, "G\u00FCltig seit")); // Ab hier VK-Basis sheet.addCell(new Label(9, 1, "VK-Basis")); sheet.addCell(new Label(10, 1, "G\u00FCltig seit")); // Nun alle aktiven Preislisten int iSpalte = 11; for (int i = 0; i < vkpfartikelpreislisteDtos.length; i++) { sheet.addCell(new Label(iSpalte, 0, vkpfartikelpreislisteDtos[i].getCNr())); sheet.addCell(new Label(iSpalte, 1, "Fixpreis")); iSpalte++; sheet.addCell(new Label(iSpalte, 1, "Rabatt")); iSpalte++; sheet.addCell(new Label(iSpalte, 1, "Errechneter Preis")); iSpalte++; sheet.addCell(new Label(iSpalte, 1, "G\u00FCltig ab")); iSpalte++; sheet.addCell(new Label(iSpalte, 1, "W\u00E4hrung")); iSpalte++; } int iRow = 2; while (resultListIterator.hasNext()) { FLRArtikelliste artikelliste = (FLRArtikelliste) resultListIterator.next(); ArtikelDto aDto = getArtikelFac().artikelFindByPrimaryKeySmall(artikelliste.getI_id(), theClientDto); sheet.addCell(new Label(0, iRow, aDto.getCNr(), numberAsTextFormat)); if (aDto.getArtikelsprDto() != null) { sheet.addCell(new Label(1, iRow, aDto.getArtikelsprDto().getCBez())); sheet.addCell(new Label(2, iRow, aDto.getArtikelsprDto().getCZbez())); } sheet.addCell(new Label(3, iRow, aDto.getEinheitCNr().trim())); ArtikellieferantDto alDto = getArtikelEinkaufspreis(artikelliste.getI_id(), new BigDecimal(1), theClientDto.getSMandantenwaehrung(), theClientDto); if (alDto != null) { if (alDto.getLieferantDto() != null) { sheet.addCell( new Label(4, iRow, alDto.getLieferantDto().getPartnerDto().formatFixName1Name2())); } if (alDto.getNEinzelpreis() != null) { sheet.addCell(new jxl.write.Number(5, iRow, alDto.getNEinzelpreis().doubleValue(), numberFormatPreis)); } if (alDto.getFRabatt() != null) { sheet.addCell(new jxl.write.Number(6, iRow, alDto.getFRabatt().doubleValue(), numberFormatRabatt)); } if (alDto.getNNettopreis() != null) { sheet.addCell(new jxl.write.Number(7, iRow, alDto.getNNettopreis().doubleValue(), numberFormatPreis)); } sheet.addCell(new jxl.write.DateTime(8, iRow, alDto.getTPreisgueltigab(), dateFormat)); } try { VkPreisfindungEinzelverkaufspreisDto preisbasisDto = getVkPreisfindungFac() .getArtikeleinzelverkaufspreis(artikelliste.getI_id(), new Date(System.currentTimeMillis()), theClientDto.getSMandantenwaehrung(), theClientDto); // Ab hier VK-Basis if (preisbasisDto != null) { sheet.addCell(new jxl.write.Number(9, iRow, preisbasisDto.getNVerkaufspreisbasis().doubleValue())); sheet.addCell(new jxl.write.DateTime(10, iRow, preisbasisDto.getTVerkaufspreisbasisgueltigab(), dateFormat)); } iSpalte = 11; for (int i = 0; i < vkpfartikelpreislisteDtos.length; i++) { // Nun fuer jede preisliste den preis holen Session sessionPreisliste = FLRSessionFactory.getFactory().openSession(); String sQueryPreisliste = "SELECT artikelpreis FROM FLRVkpfartikelpreis artikelpreis WHERE artikelpreis.vkpfartikelpreisliste_i_id=" + vkpfartikelpreislisteDtos[i].getIId() + " AND artikelpreis.artikel_i_id=" + artikelliste.getI_id() + " AND artikelpreis.t_preisgueltigab<='" + Helper.formatDateWithSlashes(new java.sql.Date(System.currentTimeMillis())) + "' ORDER BY artikelpreis.t_preisgueltigab DESC"; org.hibernate.Query queryPreisliste = session.createQuery(sQueryPreisliste); queryPreisliste.setMaxResults(1); List<?> resultListPreisliste = queryPreisliste.list(); Iterator<?> resultListIteratorPreisliste = resultListPreisliste.iterator(); if (resultListIteratorPreisliste.hasNext()) { FLRVkpfartikelpreis artikelpreis = (FLRVkpfartikelpreis) resultListIteratorPreisliste .next(); if (artikelpreis.getN_artikelfixpreis() != null) { sheet.addCell(new jxl.write.Number(iSpalte, iRow, artikelpreis.getN_artikelfixpreis().doubleValue(), numberFormatPreis)); } iSpalte++; if (artikelpreis.getN_artikelstandardrabattsatz() != null) { sheet.addCell(new jxl.write.Number(iSpalte, iRow, artikelpreis.getN_artikelstandardrabattsatz().doubleValue(), numberFormatRabatt)); } iSpalte++; String referenzRabatt = CellReferenceHelper.getCellReference(iSpalte - 1, iRow); sheet.addCell(new Formula(iSpalte, iRow, "WENN(" + CellReferenceHelper.getCellReference(iSpalte - 2, iRow) + "=0,$J" + (iRow + 1) + "*(1-" + referenzRabatt + "/100),WENN(" + referenzRabatt + "=0," + CellReferenceHelper.getCellReference(iSpalte - 2, iRow) + ",\"????\"))")); iSpalte++; Calendar c = Calendar.getInstance(); c.setTimeInMillis(artikelpreis.getT_preisgueltigab().getTime()); DateTime dateCell = new DateTime(iSpalte, iRow, c.getTime(), dateFormat); sheet.addCell(dateCell); // sheet.addCell(new jxl.write.DateTime(iSpalte, // iRow, // new Date( // artikelpreis.getT_preisgueltigab().getTime()))); iSpalte++; sheet.addCell(new Label(iSpalte, iRow, vkpfartikelpreislisteDtos[i].getWaehrungCNr())); iSpalte++; } else { iSpalte = iSpalte + 5; } sessionPreisliste.close(); } } catch (RemoteException e) { throwEJBExceptionLPRespectOld(e); } iRow++; } session.close(); workbook.write(); workbook.close(); } catch (IOException e) { throw new EJBExceptionLP(EJBExceptionLP.FEHLER, e); } catch (RowsExceededException e) { throw new EJBExceptionLP(EJBExceptionLP.FEHLER, e); } catch (WriteException e) { throw new EJBExceptionLP(EJBExceptionLP.FEHLER, e); } return os.toByteArray(); }