Example usage for org.hibernate.criterion Restrictions like

List of usage examples for org.hibernate.criterion Restrictions like

Introduction

In this page you can find the example usage for org.hibernate.criterion Restrictions like.

Prototype

public static SimpleExpression like(String propertyName, String value, MatchMode matchMode) 

Source Link

Document

Apply a "like" constraint to the named property using the provided match mode

Usage

From source file:au.edu.uts.eng.remotelabs.schedserver.permissions.pages.UsersPage.java

License:Open Source License

/**
 * Gets a list of users with a specific search term. The users may be 
 * excluded from a specific class. /*www  . j  av  a2s  .  co  m*/
 * 
 * @param request
 * @return response
 * @throws Exception
 */
@SuppressWarnings("unchecked")
public JSONArray list(HttpServletRequest request) throws JSONException {
    JSONArray arr = new JSONArray();

    Criteria qu = this.db.createCriteria(User.class);

    String search = request.getParameter("search");
    if (search != null) {
        /* Search filter. */
        qu.add(Restrictions.disjunction().add(Restrictions.like("name", search, MatchMode.ANYWHERE))
                .add(Restrictions.like("firstName", search, MatchMode.ANYWHERE))
                .add(Restrictions.like("lastName", search, MatchMode.ANYWHERE)));
    }

    if (request.getParameter("max") != null) {
        /* Max results. */
        qu.setMaxResults(Integer.parseInt(request.getParameter("max")));
    }

    if (request.getParameter("in") != null) {
        /* Users in class. */
        UserClass inClass = new UserClassDao(this.db).findByName(request.getParameter("in"));
        if (inClass == null) {
            this.logger.warn("Not going to add in class as a user list restriction because the class '"
                    + request.getParameter("in") + "' was not found.");
        } else {
            qu.createCriteria("userAssociations").add(Restrictions.eq("userClass", inClass));
        }
    }

    if (request.getParameter("notIn") != null) {
        /* Users not in class. */
        UserClass notInClass = new UserClassDao(this.db).findByName(request.getParameter("notIn"));
        if (notInClass == null) {
            this.logger.warn("Not going to add not in class as a user list restriction because the class '"
                    + request.getParameter("notIn") + "' was not found.");
        } else {
            DetachedCriteria subQu = DetachedCriteria.forClass(User.class)
                    .setProjection(Property.forName("name")).createCriteria("userAssociations")
                    .add(Restrictions.eq("userClass", notInClass));

            List<String> names = subQu.getExecutableCriteria(this.db).list();
            if (names.size() > 0) {
                qu.add(Restrictions.not(Restrictions.in("name", names)));
            }
        }
    }

    qu.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
    qu.addOrder(Order.asc("lastName"));
    qu.addOrder(Order.asc("name"));

    for (User user : (List<User>) qu.list()) {
        JSONObject uo = new JSONObject();
        uo.put("name", user.getNamespace() + "-_-" + user.getName());

        if (user.getFirstName() == null || user.getLastName() == null) {
            uo.put("display", user.getName());
        } else {
            uo.put("display", user.getLastName() + ", " + user.getFirstName());
        }

        arr.put(uo);
    }

    return arr;
}

From source file:au.edu.uts.eng.remotelabs.schedserver.reports.intf.Reports.java

License:Open Source License

@SuppressWarnings("unchecked")
@Override/*w w w . j av a 2 s  . co  m*/
public QueryInfoResponse queryInfo(final QueryInfo queryInfo) {
    /** Request parameters. **/
    final QueryInfoType qIReq = queryInfo.getQueryInfo();
    String debug = "Received " + this.getClass().getSimpleName() + "#queryInfo with params:";
    debug += "Requestor: " + qIReq.getRequestor() + ", QuerySelect: " + qIReq.getQuerySelect();
    if (qIReq.getQueryFilter() != null) {
        debug += ", QueryFilter: " + qIReq.getQueryFilter();
    }
    debug += ", limit: " + qIReq.getLimit();
    this.logger.debug(debug);
    final RequestorType uid = qIReq.getRequestor();

    /** Response parameters. */
    final QueryInfoResponse resp = new QueryInfoResponse();
    final QueryInfoResponseType respType = new QueryInfoResponseType();
    respType.setTypeForQuery(TypeForQuery.RIG);
    resp.setQueryInfoResponse(respType);

    final org.hibernate.Session ses = DataAccessActivator.getNewSession();

    /* First Query Filter - this contains the main selection type to be selected */
    final QueryFilterType query0 = qIReq.getQuerySelect();

    try {
        Criteria cri;

        /* ----------------------------------------------------------------
         * -- Load the requestor.                                             --
         * ---------------------------------------------------------------- */
        final User user = this.getUserFromUserID(uid, ses);
        if (user == null) {
            this.logger.info("Unable to generate report because the user has not been found. Supplied "
                    + "credentials ID=" + uid.getUserID() + ", namespace=" + uid.getUserNamespace() + ", "
                    + "name=" + uid.getUserName() + '.');
            return resp;
        }
        final String persona = user.getPersona();

        /* Check for type of query to determine selection parameters */
        if (query0.getTypeForQuery() == TypeForQuery.RIG) {
            /* ----------------------------------------------------------------
             * -- Rig Information only available to ADMIN, to be mediated    --
             * -- by interface. No criteria on Requestor                     --
             * ---------------------------------------------------------------- */

            cri = ses.createCriteria(Rig.class);
            if (query0.getQueryLike() != null) {
                cri.add(Restrictions.like("name", query0.getQueryLike(), MatchMode.ANYWHERE));
            }
            if (qIReq.getLimit() > 0)
                cri.setMaxResults(qIReq.getLimit());

            cri.addOrder(Order.asc("name"));
            for (final Rig o : (List<Rig>) cri.list()) {
                respType.addSelectionResult(o.getName());
            }
        } else if (query0.getTypeForQuery() == TypeForQuery.RIG_TYPE) {
            /* ----------------------------------------------------------------
             * -- Rig Type Information only available to ADMIN, to be        -- 
             * -- mediated by interface. No criteria on Requestor            --
             * ---------------------------------------------------------------- */
            cri = ses.createCriteria(RigType.class);

            if (query0.getQueryLike() != null) {
                cri.add(Restrictions.like("name", query0.getQueryLike(), MatchMode.ANYWHERE));
            }
            if (qIReq.getLimit() > 0)
                cri.setMaxResults(qIReq.getLimit());
            cri.addOrder(Order.asc("name"));
            for (final RigType o : (List<RigType>) cri.list()) {
                respType.addSelectionResult(o.getName());
            }
        } else if (query0.getTypeForQuery() == TypeForQuery.USER_CLASS) {
            cri = ses.createCriteria(UserClass.class);

            if (query0.getQueryLike() != null) {
                cri.add(Restrictions.like("name", query0.getQueryLike(), MatchMode.ANYWHERE));
            }
            if (qIReq.getLimit() > 0)
                cri.setMaxResults(qIReq.getLimit());
            cri.addOrder(Order.asc("name"));

            /* ----------------------------------------------------------------
            * Check that the requestor has permissions to request the report.
            * If persona = USER, no reports (USERs will not get here)
            * If persona = ADMIN, any report 
            * If persona = ACADEMIC, only for classes they own if they can generate reports
            * ---------------------------------------------------------------- */

            if (User.ACADEMIC.equals(persona)) {
                DetachedCriteria apList = DetachedCriteria.forClass(AcademicPermission.class, "ap")
                        .add(Restrictions.eq("ap.canGenerateReports", true))
                        .setProjection(Property.forName("userClass"));

                cri.add(Subqueries.propertyIn("id", apList));

                for (final UserClass o : (List<UserClass>) cri.list()) {
                    respType.addSelectionResult(o.getName());
                }
            } else if (User.ADMIN.equals(persona)) {
                for (final UserClass o : (List<UserClass>) cri.list()) {
                    respType.addSelectionResult(o.getName());
                }
            }
        } else if (query0.getTypeForQuery() == TypeForQuery.USER) {
            cri = ses.createCriteria(User.class, "u");

            /* ----------------------------------------------------------------
             * If persona = USER, no reports (USERs will not get here)
             * If persona = ADMIN, any report 
             * If persona = ACADEMIC, only for users in classes they own if they can genrate reports
             * ---------------------------------------------------------------- */

            if (query0.getQueryLike() != null) {
                cri.add(Restrictions.like("name", query0.getQueryLike(), MatchMode.ANYWHERE));
            }
            if (qIReq.getLimit() > 0)
                cri.setMaxResults(qIReq.getLimit());
            cri.addOrder(Order.asc("name"));

            if (User.ACADEMIC.equals(persona)) {
                DetachedCriteria apList = DetachedCriteria.forClass(AcademicPermission.class, "ap")
                        .add(Restrictions.eq("ap.canGenerateReports", true))
                        .setProjection(Property.forName("userClass"));

                DetachedCriteria userList = DetachedCriteria.forClass(UserAssociation.class, "ua")
                        .add(Subqueries.propertyIn("ua.userClass", apList))
                        .setProjection(Property.forName("user.id"));

                cri.add(Subqueries.propertyIn("id", userList));

                for (final User o : (List<User>) cri.list()) {
                    respType.addSelectionResult(o.getNamespace() + ':' + o.getName());
                }
            } else if (User.ADMIN.equals(persona)) {
                for (final User o : (List<User>) cri.list()) {
                    respType.addSelectionResult(o.getNamespace() + ':' + o.getName());
                }
            }
        } else if (query0.getTypeForQuery() == TypeForQuery.REQUEST_CAPABILITIES) {
            cri = ses.createCriteria(RequestCapabilities.class);
            if (query0.getQueryLike() != null) {
                cri.add(Restrictions.like("capabilities", query0.getQueryLike(), MatchMode.ANYWHERE));
            }
            if (qIReq.getLimit() > 0)
                cri.setMaxResults(qIReq.getLimit());
            cri.addOrder(Order.asc("capabilities"));
            final List<RequestCapabilities> list = cri.list();
            for (final RequestCapabilities o : list) {
                respType.addSelectionResult(o.getCapabilities());
            }
        } else {
            this.logger.error(
                    "QueryInfo request failed because TypeForQuery does not have a valid value.  Value is "
                            + query0.getTypeForQuery().toString());
            return resp;
        }

        final QueryFilterType filter[] = qIReq.getQueryFilter();
        if (filter != null) {
            //DODGY Designed, not implemented
        }
    } finally {
        ses.close();
    }

    respType.setTypeForQuery(query0.getTypeForQuery());
    resp.setQueryInfoResponse(respType);

    return resp;
}

From source file:au.org.theark.core.dao.StudyDao.java

License:Open Source License

private List<Long> applyConsentStatusFilters(DataExtractionVO allTheData, Search search,
        List<Long> idsToInclude) {

    //for(Long l : idsToInclude) {
    //   log.info("including: " + l);
    //}//from   ww  w . jav  a 2  s .co  m
    boolean hasConsentFilters = false;
    if (search.getQueryFilters().isEmpty()) {
        return idsToInclude;
    } else {
        for (QueryFilter filter : search.getQueryFilters()) {
            if (filter.getConsentStatusField() != null) {
                hasConsentFilters = true;
            }
        }
    }
    Criteria filter = getSession().createCriteria(Consent.class, "c");
    filter.add(Restrictions.eq("c.study.id", search.getStudy().getId()));
    filter.createAlias("c.linkSubjectStudy", "lss");
    if (!idsToInclude.isEmpty()) {
        filter.add(Restrictions.in("lss.id", idsToInclude));
    }
    filter.createAlias("c.studyComponentStatus", "cscs");
    filter.createAlias("c.studyComp", "csc");

    if (!hasConsentFilters) {

        for (QueryFilter qf : search.getQueryFilters()) {
            if (qf.getConsentStatusField() != null) {
                switch (qf.getOperator()) {
                case EQUAL:
                    filter.add(Restrictions.eq(getConsentFilterFieldName(qf), qf.getValue()));
                    break;
                case BETWEEN:
                    filter.add(Restrictions.between(getConsentFilterFieldName(qf), qf.getValue(),
                            qf.getSecondValue()));
                    break;
                case GREATER_THAN:
                    filter.add(Restrictions.gt(getConsentFilterFieldName(qf), qf.getValue()));
                    break;
                case GREATER_THAN_OR_EQUAL:
                    filter.add(Restrictions.ge(getConsentFilterFieldName(qf), qf.getValue()));
                    break;
                case IS_EMPTY:
                    filter.add(Restrictions.isEmpty(getConsentFilterFieldName(qf)));
                    break;
                case IS_NOT_EMPTY:
                    filter.add(Restrictions.isNotEmpty(getConsentFilterFieldName(qf)));
                    break;
                case LESS_THAN:
                    filter.add(Restrictions.lt(getConsentFilterFieldName(qf), qf.getValue()));
                    break;
                case LESS_THAN_OR_EQUAL:
                    filter.add(Restrictions.le(getConsentFilterFieldName(qf), qf.getValue()));
                    break;
                case LIKE:
                    filter.add(Restrictions.like(getConsentFilterFieldName(qf), qf.getValue(),
                            MatchMode.ANYWHERE));
                    break;
                case NOT_EQUAL:
                    filter.add(Restrictions.ne(getConsentFilterFieldName(qf), qf.getValue()));
                    break;
                default:
                    break;
                }
            }
        }
    }
    filter.setProjection(
            Projections.distinct(Projections.projectionList().add(Projections.property("lss.id"))));

    List<Long> consentStatusIDs = filter.list();

    Collection<Consent> csData = Collections.EMPTY_LIST;

    if (!consentStatusIDs.isEmpty()) {
        Criteria consentData = getSession().createCriteria(Consent.class, "c");
        consentData.add(Restrictions.eq("c.study.id", search.getStudy().getId()));
        consentData.createAlias("c.linkSubjectStudy", "lss");
        consentData.add(Restrictions.in("lss.id", consentStatusIDs));
        csData = consentData.list();
    }

    HashMap<String, ExtractionVO> hashOfConsentStatusData = allTheData.getConsentStatusData();

    ExtractionVO valuesForThisLss = new ExtractionVO();
    HashMap<String, String> map = null;
    LinkSubjectStudy previousLss = null;
    int count = 0;
    //will try to order our results and can therefore just compare to last LSS and either add to or create new Extraction VO
    for (Consent data : csData) {
        if (previousLss == null) {
            map = new HashMap<String, String>();
            previousLss = data.getLinkSubjectStudy();
            count = 0;
        } else if (data.getLinkSubjectStudy().getId().equals(previousLss.getId())) {
            //then just put the data in
            count++;
        } else { //if its a new LSS finalize previous map, etc
            valuesForThisLss.setKeyValues(map);
            valuesForThisLss.setSubjectUid(previousLss.getSubjectUID());
            hashOfConsentStatusData.put(previousLss.getSubjectUID(), valuesForThisLss);
            previousLss = data.getLinkSubjectStudy();
            map = new HashMap<String, String>();//reset
            valuesForThisLss = new ExtractionVO();
            count = 0;
        }
        if (data.getStudyComp().getName() != null) {
            map.put(count + "_Study Component Name", data.getStudyComp().getName());
        }
        if (data.getStudyComponentStatus() != null) {
            map.put(count + "_Study Component Status", data.getStudyComponentStatus().getName());
        }
        if (data.getConsentDate() != null) {
            map.put(count + "_Consent Date", data.getConsentDate().toString());
        }
        if (data.getConsentedBy() != null) {
            map.put(count + "_Consented By", data.getConsentedBy());
        }
    }

    //finalize the last entered key value sets/extraction VOs
    if (map != null && previousLss != null) {
        valuesForThisLss.setKeyValues(map);
        valuesForThisLss.setSubjectUid(previousLss.getSubjectUID());
        hashOfConsentStatusData.put(previousLss.getSubjectUID(), valuesForThisLss);
    }

    //can probably now go ahead and add these to the dataVO...even though inevitable further filters may further axe this list or parts of it.
    allTheData.setConsentStatusData(hashOfConsentStatusData);
    if (hasConsentFilters) {
        return consentStatusIDs;
    } else {
        return idsToInclude;
    }
}

From source file:au.org.theark.core.dao.StudyDao.java

License:Open Source License

@Override
public List<Search> getSearchesForSearch(Search search) {
    Criteria criteria = getSession().createCriteria(Search.class);
    criteria.add(Restrictions.eq("study", search.getStudy()));
    if (search.getId() != null) {
        criteria.add(Restrictions.eq("id", search.getId()));
    }/*from  ww w .j  a va2  s  .c  o m*/
    if (search.getName() != null) {
        criteria.add(Restrictions.like("name", search.getName(), MatchMode.ANYWHERE));
    }
    List<Search> searchList = criteria.list();
    return searchList;
}

From source file:br.al.contractmanager.dao.UsuarioDao.java

@Transactional(readOnly = true)
public List<Usuario> buscar(String termo) {
    Session session = sessionFactory.getCurrentSession();
    return session.createCriteria(Usuario.class)
            .add(Restrictions.or(Restrictions.eq("matricula", termo),
                    Restrictions.like("nomeUsuario", termo, MatchMode.ANYWHERE).ignoreCase(),
                    Restrictions.like("nomeCompleto", termo, MatchMode.ANYWHERE).ignoreCase()))
            .setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY).list();
}

From source file:br.al.contractmanager.dao.UsuarioDao.java

@Transactional(readOnly = true)
public int count(String termo) {
    Session session = sessionFactory.getCurrentSession();
    try {//w ww.  j av a  2 s.c  o  m
        Criteria criteria = session.createCriteria(Usuario.class);
        criteria.add(Restrictions.or(Restrictions.eq("matricula", termo),
                Restrictions.like("nomeUsuario", termo, MatchMode.ANYWHERE).ignoreCase(),
                Restrictions.like("nomeCompleto", termo, MatchMode.ANYWHERE).ignoreCase()))
                .setProjection(Projections.distinct(Projections.id()));
        return ((Long) criteria.setProjection(Projections.rowCount()).uniqueResult()).intValue();
    } catch (HibernateException e) {
        System.out.println(e.getMessage());
        return 0;
    }
}

From source file:br.com.cwi.crescer.aula3.dao.PessoaDao.java

public List<Pessoa> findByNome(String nmPessoa) {
    final Session session = entityManager.unwrap(Session.class);
    final Criteria criteria = session.createCriteria(Pessoa.class);
    criteria.add(Restrictions.like("nmPessoa", nmPessoa, ANYWHERE));
    return criteria.list();
}

From source file:br.com.cwi.crescer.exemplohibernate.dao.PessoaDao.java

public List<Pessoa> findByName(String nmPessoa) {
    final Session session = em.unwrap(Session.class);
    Criteria criteria = session.createCriteria(Pessoa.class);
    //ANYWHERE -> insere %% entre o nome
    criteria.add(Restrictions.like("nmPessoa", nmPessoa, ANYWHERE));
    return criteria.list();
}

From source file:br.com.lsi.ordemservico.dao.EquipamentoDAO.java

@Override
public List<Equipamento> buscaPorNome(String nome) throws DAOException {
    List<Equipamento> lista = new ArrayList<>();
    Session sessoa = PersistenceUtil.getSessionFactory().openSession();
    try {//from www  . j  a  va2 s  .  c  om
        sessoa.getTransaction().begin();
        Criteria criteria = sessoa.createCriteria(Equipamento.class);
        criteria.add(Restrictions.like("descricao", nome, MatchMode.ANYWHERE));
        lista = criteria.list();
    } catch (Exception e) {
        e.printStackTrace();
        throw new DAOException("Erro ao buscar por Descrio no BD");
    } finally {
        sessoa.close();
    }
    return lista;
}

From source file:br.com.magmadoctor.modelo.convenio.ConvenioDAOHibernate.java

@Override
public List<Convenio> listarPorNome(String nome) {
    List<Convenio> lista;//from w  w  w .  ja  va 2 s . co m
    Criteria resultado = this.session.createCriteria(Convenio.class)
            .add(Restrictions.like("nomeFantasia", nome, MatchMode.ANYWHERE))
            .addOrder(Order.asc("nomeFantasia"));
    lista = resultado.list();
    return lista;
}