Example usage for org.hibernate Filter setParameter

List of usage examples for org.hibernate Filter setParameter

Introduction

In this page you can find the example usage for org.hibernate Filter setParameter.

Prototype

public Filter setParameter(String name, Object value);

Source Link

Document

Set the named parameter's value for this filter.

Usage

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;/*from  w  w w . j  ava  2  s. c o m*/
    }

    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.devnexus.ting.repository.jpa.ScheduleItemRepositoryImpl.java

License:Apache License

/** {@inheritDoc} */
@Override//from w  w  w  .j a  va  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

/**
 * https://hibernate.onjira.com/browse/HHH-6902
 *///from w  w  w.j  a  v  a 2  s. c  om
@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.hibernate.dao.AsesinosDAO.java

@Override
public List<Asesinos> getAsesinoByCantidadAsesinato(int cantasesinato) {
    Filter filter = session.enableFilter("asesinosFilter");
    filter.setParameter("maxcantasesinatos", cantasesinato);
    session.beginTransaction();/* w w w  . j  av a  2s.com*/
    List<Asesinos> personaEdadList = session.createQuery("from Asesinos").list();
    return personaEdadList;
}

From source file:com.masetta.spann.orm.hibernate.integration.FilterActivationsTest.java

License:Apache License

private Session expectFilterEnable(String filter, boolean alreadyEnabled, Object... params) {
    Session session = expectSessionAccess();
    EasyMock.expect(session.getEnabledFilter(filter))
            .andReturn(alreadyEnabled ? createMock(Filter.class) : null);

    Filter filterMock = createMock(Filter.class);
    EasyMock.expect(session.enableFilter(filter)).andReturn(filterMock);

    for (int i = 0; i < params.length;) {
        filterMock.setParameter((String) params[i++], params[i++]);
        EasyMock.expectLastCall().andReturn(filterMock);
    }// w w w. j  ava 2s  . co  m

    filterMock.validate();
    EasyMock.expectLastCall();

    return session;
}

From source file:com.masetta.spann.orm.hibernate.support.HibernateSupport.java

License:Apache License

private static List<String> enableFilters(Session session, Collection<FilterActivation> filterList) {

    if (filterList == null || filterList.isEmpty())
        return Collections.emptyList();

    List<String> applied = new ArrayList<String>();
    Filter filter;
    for (FilterActivation f : filterList) {
        String filterName = f.getName();

        Collection<Map.Entry<String, Object>> parameters = f.getParameters();
        // skip filters which are already enabled,
        filter = session.getEnabledFilter(filterName);
        if (filter != null) {
            if (f.getParameters().size() > 0) {
                throw new IllegalArgumentException("Filter '" + f.getName()
                        + "' is already activated. Can not enable filter with different arguments.");
            }/*ww w .j av  a 2s. com*/
            continue;
        }

        filter = session.enableFilter(filterName);
        applied.add(filterName);
        for (Map.Entry<String, Object> e : parameters) {
            Object value = e.getValue();
            if (value == null) {
                filter.setParameter(e.getKey(), value);
            } else if (value instanceof Collection) {
                filter.setParameterList(e.getKey(), (Collection) value);
            } else if (value.getClass().isArray()) {
                filter.setParameterList(e.getKey(), (Object[]) value);
            } else {
                filter.setParameter(e.getKey(), value);
            }
        }
        filter.validate();
    }
    return applied;
}

From source file:edu.purdue.cybercenter.dm.web.TermController.java

private String fetchAllTerms(HttpServletRequest request, HttpServletResponse response, boolean isTemplate) {
    Session session = DomainObjectHelper.getHbmSession();

    Filter filter = session.enableFilter("mostRecentUpdatedTermFilter");
    filter.setParameter("isTemplate", isTemplate);
    Filter assetStatusFilter = session.enableFilter("assetStatusFilter");
    assetStatusFilter.setParameterList("statusIds", Arrays.asList(1));
    String responseBody = listTerms(request, response, isTemplate ? "template" : "term");
    session.disableFilter("assetStatusFilter");
    session.disableFilter("mostRecentUpdatedTermFilter");

    return responseBody;
}

From source file:gov.nih.nci.security.authorization.instancelevel.InstanceLevelSecurityHelper.java

License:BSD License

/**
 * This method initializes the filter that are already added to the Sessionfactory.
 * <br>/*from   w  w w. j  a v  a 2 s.  c  o m*/
 * This method also initializes the defined filters configured in HBM/Classes/Packages based on the definedFilterNamesMap. 
 * If definedFilterNamesMap contains 'ALL' as the Filter Name (key) then all defined filters are enabled.
 * <br>
 * This method first obtains the list of all the defined filters from the SessionFactory in the passes Session object. 
 * It then just iterates through the filter list and sets the group names and the application name parameter. 
 * 
 * @param groupNames The names of the groups which are invoking the query
 * @param session The Hibernate Session initialized to execute this query
 * @param authorizationManager The CSM AuthorizationManager instance for this application
 * @param definedFilterNamesMap - Map of defined Filter Names and string value ( enable / disable ) to indicate that the filter should be enabled of disabled.<br>.
 *                            
 */
public static void initializeFiltersForGroups(String[] groupNames, Session session,
        AuthorizationManager authorizationManager, Map<String, String> definedFilterNamesMap) {

    List<String> sessionGroupFilterNamesList = new ArrayList<String>();
    List<String> sessionDefinedFilterNamesList = new ArrayList<String>();
    boolean enableAllDefinedFilterNames = false;

    Set definedFilterNames = null;
    if (definedFilterNamesMap != null && !definedFilterNamesMap.isEmpty()) {
        definedFilterNames = definedFilterNamesMap.keySet();
        if (definedFilterNames.contains("ALL"))
            enableAllDefinedFilterNames = true;
    }

    SessionFactory sessionFactory = session.getSessionFactory();
    Set sessionFilterNamesSet = sessionFactory.getDefinedFilterNames();

    Iterator sessionFilterNamesSetIterator = sessionFilterNamesSet.iterator();
    while (sessionFilterNamesSetIterator.hasNext()) {
        String filterName = (String) sessionFilterNamesSetIterator.next();

        if (null != definedFilterNames) {
            if (enableAllDefinedFilterNames) {
                sessionDefinedFilterNamesList.add(filterName);
            } else {
                if (definedFilterNames.contains(filterName)) {
                    String value = (String) definedFilterNamesMap.get(filterName);
                    if (Constants.ENABLE.equalsIgnoreCase(value)) {
                        sessionDefinedFilterNamesList.add(filterName);
                    }
                }
            }
        }
        FilterDefinition filterDefinition = sessionFactory.getFilterDefinition(filterName);
        if (filterDefinition != null) {

            Set<String> parameterNamesSet = filterDefinition.getParameterNames();
            if (parameterNamesSet != null && parameterNamesSet.contains("GROUP_NAMES")) {
                sessionGroupFilterNamesList.add(filterName);
                // remove this filter name from sessionDefinedFilterNamesList if it exists in there.
                if (sessionDefinedFilterNamesList.contains(filterName))
                    sessionDefinedFilterNamesList.remove(filterName);
            }
        }
    }

    //Enable the User Filters from CSM database for the application
    Iterator sessionGroupFilterNamesListIterator = sessionGroupFilterNamesList.iterator();
    while (sessionGroupFilterNamesListIterator.hasNext()) {
        String filterName = (String) sessionGroupFilterNamesListIterator.next();
        Filter filter = session.enableFilter(filterName);
        filter.setParameterList("GROUP_NAMES", groupNames);
        filter.setParameter("APPLICATION_ID", authorizationManager.getApplicationContext().getApplicationId());
    }
    //Enable the Defined Filters available in HBM/Classes.
    Iterator sessionDefinedFilterNamesListIterator = sessionDefinedFilterNamesList.iterator();
    while (sessionDefinedFilterNamesListIterator.hasNext()) {
        String filterName = (String) sessionDefinedFilterNamesListIterator.next();
        Filter filter = session.enableFilter(filterName);
    }
}

From source file:gov.nih.nci.security.authorization.instancelevel.InstanceLevelSecurityHelper.java

License:BSD License

/**
 * This method initializes the User filter from CSM Database that are already added to the Sessionfactory.
 * <br>/*w ww .ja v  a 2  s. c o  m*/
 * This method also initializes the defined filters configured in HBM/Classes/Packages based on the definedFilterNamesMap.
 * If definedFilterNamesMap contains 'ALL' as the Filter Name (key) then all defined filters are enabled. 
 * <br>
 * This method first obtains the list of all the defined filters from the SessionFactory in the passes Session object. 
 * It then just iterates through the filter list and sets the user name and the application name parameter. 
 * 
 * @param userName The name of the logged in user or group which is invoking the query
 * @param session The Hibernate Session initialized to execute this query
 * @param authorizationManager The CSM AuthorizationManager instance for this application
 * @param definedFilterNamesMap - Map of defined Filter Names and string value ( enable / disable ) to indicate that the filter should be enabled of disabled.
 * 
 */
public static void initializeFilters(String userName, Session session,
        AuthorizationManager authorizationManager, Map<String, String> definedFilterNamesMap) {
    List<String> initUserFilterNames = new ArrayList<String>();
    List<String> initSessionDefinedFilterNames = new ArrayList<String>();

    boolean enableAllSessionDefinedFilters = false;

    Set definedFilterNames = null;
    if (definedFilterNamesMap != null && !definedFilterNamesMap.isEmpty()) {
        definedFilterNames = definedFilterNamesMap.keySet();
        if (definedFilterNames.contains("ALL"))
            enableAllSessionDefinedFilters = true;
    }

    Iterator sessionFilterNamesSetIterator = session.getSessionFactory().getDefinedFilterNames().iterator();
    while (sessionFilterNamesSetIterator.hasNext()) {
        String filterName = (String) sessionFilterNamesSetIterator.next();
        if (enableAllSessionDefinedFilters) {
            initSessionDefinedFilterNames.add(filterName);
        } else if (definedFilterNames != null && definedFilterNames.contains(filterName)) {
            String value = (String) definedFilterNamesMap.get(filterName);
            if (Constants.ENABLE.equalsIgnoreCase(value)) {
                initSessionDefinedFilterNames.add(filterName);
            }
        }

        FilterDefinition filterDefinition = session.getSessionFactory().getFilterDefinition(filterName);
        if (filterDefinition != null) {
            Set<String> parameterNamesSet = filterDefinition.getParameterNames();
            if (parameterNamesSet != null && parameterNamesSet.contains("USER_NAME")) {
                initUserFilterNames.add(filterName);
                // remove this filter name from sessionDefinedFilterNamesList if it exists in there.
                initSessionDefinedFilterNames.remove(filterName);
            }
        }
    }

    //Enable the User Filters from CSM database for the application
    Iterator sessionUserFilterNamesListIterator = initUserFilterNames.iterator();
    while (sessionUserFilterNamesListIterator.hasNext()) {
        String filterName = (String) sessionUserFilterNamesListIterator.next();
        Filter filter = session.enableFilter(filterName);
        filter.setParameter("USER_NAME", userName);
        filter.setParameter("APPLICATION_ID", authorizationManager.getApplicationContext().getApplicationId());
    }
    //Enable the Defined Filters available in HBM/Classes.
    Iterator sessionDefinedFilterNamesListIterator = initSessionDefinedFilterNames.iterator();
    while (sessionDefinedFilterNamesListIterator.hasNext()) {
        String filterName = (String) sessionDefinedFilterNamesListIterator.next();
        Filter filter = session.enableFilter(filterName);
    }
}