Java Examples for org.hibernate.criterion.MatchMode

The following java examples will help you to understand the usage of org.hibernate.criterion.MatchMode. These source code samples are taken from different open source projects.

Example 1
Project: Doctors-master  File: PerfilUsuarioDao.java View source code
// mudar p/ UsuarioInvalidoException.
public PerfilUsuario logar(PerfilUsuario usuario) throws UsuarioInvalidoException {
    Criteria criteria = getSession().createCriteria(PerfilUsuario.class).add(Restrictions.ilike("login", usuario.getLogin(), MatchMode.EXACT)).add(Restrictions.ilike("senha", usuario.getSenha(), MatchMode.EXACT));
    PerfilUsuario user = (PerfilUsuario) criteria.uniqueResult();
    if (user == null) {
        throw new UsuarioInvalidoException("Usuário Inválido!");
    }
    return user;
}
Example 2
Project: RBAC-master  File: AccountDao.java View source code
/**
	 * æ ¹æ?®ç”¨æˆ·ç™»å½•å??和用户显示å??查找用户列表
	 * @param username
	 * @param realname
	 * @return
	 */
public List<SysAccount> getSysAccountList(String username, String realname) {
    Criteria crit = super.getSession().createCriteria(SysAccount.class);
    crit.add(Restrictions.eq("isDeleted", 0));
    if (CommonUtils.isNotEmpty(username)) {
        crit.add(Restrictions.ilike("username", username, MatchMode.ANYWHERE));
    }
    if (CommonUtils.isNotEmpty(realname)) {
        crit.add(Restrictions.ilike("realname", realname, MatchMode.ANYWHERE));
    }
    return crit.list();
}
Example 3
Project: breeze.server.java-master  File: CriteriaBuilder.java View source code
private Criterion createCriterion(CriteriaWrapper crit, BinaryPredicate pred, String contextAlias) {
    Operator op = pred.getOperator();
    String symbol = _operatorMap.get(op.getName());
    Expression expr1 = pred.getExpr1();
    Expression expr2 = pred.getExpr2();
    Criterion cr;
    if (expr1 instanceof PropExpression) {
        PropExpression pexpr1 = (PropExpression) expr1;
        String propPath = pexpr1.getPropertyPath();
        String propName;
        if (pexpr1.getProperty().getParentType().isComplexType()) {
            // don't process the property path in this case.
            propName = propPath;
        } else {
            propName = _aliasBuilder.getPropertyName(crit, propPath);
        }
        propName = (contextAlias == null) ? propName : contextAlias + "." + propName;
        if (expr2 instanceof LitExpression) {
            Object value = ((LitExpression) expr2).getValue();
            if (value == null) {
                if (op == Operator.Equals) {
                    cr = Restrictions.isNull(propName);
                } else if (op == Operator.NotEquals) {
                    cr = Restrictions.isNotNull(propName);
                } else {
                    throw new RuntimeException("Binary Predicate with a null value and the " + op.getName() + "operator is not supported .");
                }
            } else if (symbol != null) {
                cr = new OperatorExpression(propName, value, symbol);
            } else if (op == Operator.In) {
                cr = Restrictions.in(propName, ((List) value).toArray());
            } else if (op == Operator.StartsWith) {
                cr = Restrictions.like(propName, ((String) value), MatchMode.START);
            } else if (op == Operator.EndsWith) {
                cr = Restrictions.like(propName, (String) value, MatchMode.END);
            } else if (op == Operator.Contains) {
                cr = Restrictions.like(propName, ((String) value), MatchMode.ANYWHERE);
            } else {
                throw new RuntimeException("Binary Predicate with the " + op.getName() + "operator is not yet supported.");
            }
        } else {
            // javax.persistence.criteria.CriteriaBuilder x = new
            // javax.persistence.criteria.CriteriaBuilder();
            String otherPropPath = ((PropExpression) expr2).getPropertyPath();
            if (symbol != null) {
                cr = new PropertyExpression(propName, otherPropPath, symbol);
            } else if (op == Operator.StartsWith) {
                cr = new LikePropertyExpression(propName, otherPropPath, MatchMode.START);
            } else if (op == Operator.EndsWith) {
                cr = new LikePropertyExpression(propName, otherPropPath, MatchMode.END);
            } else if (op == Operator.Contains) {
                cr = new LikePropertyExpression(propName, otherPropPath, MatchMode.ANYWHERE);
            } else {
                throw new RuntimeException("Property comparison with the " + op.getName() + "operator is not yet supported.");
            }
        }
        return cr;
    } else {
        throw new RuntimeException("Function expressions not yet supported.");
    }
}
Example 4
Project: cagrid2-master  File: AbstractDao.java View source code
@SuppressWarnings("unchecked")
public List<T> searchByExample(final T sample, final boolean inexactMatches) {
    return (List<T>) getHibernateTemplate().execute(new HibernateCallback() {

        public Object doInHibernate(Session session) throws HibernateException, SQLException {
            Example example = Example.create(sample).excludeZeroes();
            if (inexactMatches) {
                example.ignoreCase().enableLike(MatchMode.ANYWHERE);
            }
            return session.createCriteria(domainClass()).add(example).list();
        }
    });
}
Example 5
Project: curso-javaee-primefaces-master  File: Pedidos.java View source code
@SuppressWarnings("unchecked")
public List<Pedido> filtrados(PedidoFilter filtro) {
    Session session = this.manager.unwrap(Session.class);
    Criteria criteria = session.createCriteria(Pedido.class).createAlias(// fazemos uma associação (join) com cliente e nomeamos como "c"
    "cliente", "c").createAlias(// fazemos uma associação (join) com vendedor e nomeamos como "v"
    "vendedor", "v");
    if (filtro.getNumeroDe() != null) {
        // id deve ser maior ou igual (ge = greater or equals) a filtro.numeroDe
        criteria.add(Restrictions.ge("id", filtro.getNumeroDe()));
    }
    if (filtro.getNumeroAte() != null) {
        // id deve ser menor ou igual (le = lower or equal) a filtro.numeroDe
        criteria.add(Restrictions.le("id", filtro.getNumeroAte()));
    }
    if (filtro.getDataCriacaoDe() != null) {
        criteria.add(Restrictions.ge("dataCriacao", filtro.getDataCriacaoDe()));
    }
    if (filtro.getDataCriacaoAte() != null) {
        criteria.add(Restrictions.le("dataCriacao", filtro.getDataCriacaoAte()));
    }
    if (StringUtils.isNotBlank(filtro.getNomeCliente())) {
        // acessamos o nome do cliente associado ao pedido pelo alias "c", criado anteriormente
        criteria.add(Restrictions.ilike("c.nome", filtro.getNomeCliente(), MatchMode.ANYWHERE));
    }
    if (StringUtils.isNotBlank(filtro.getNomeVendedor())) {
        // acessamos o nome do vendedor associado ao pedido pelo alias "v", criado anteriormente
        criteria.add(Restrictions.ilike("v.nome", filtro.getNomeVendedor(), MatchMode.ANYWHERE));
    }
    if (filtro.getStatuses() != null && filtro.getStatuses().length > 0) {
        // adicionamos uma restrição "in", passando um array de constantes da enum StatusPedido
        criteria.add(Restrictions.in("status", filtro.getStatuses()));
    }
    return criteria.addOrder(Order.asc("id")).list();
}
Example 6
Project: issuetracker-master  File: IssueServiceImpl.java View source code
/**
	 * metodo invocado toda vez que uma lazy datatable de um MB(ex:  <p:datatable value="#{issueBean.dataModel}") que usa
	 * esta service for atualizada(via ajax ou não)
	 */
@Override
public Criteria configPagination(SearchModel<Issue> searchModel) {
    Criteria crit = getCriteria();
    //configura paginação para o dashboard
    //parametro passado atraves do mapa de parametros {@see DashboardBean#preload()}
    Long idUsuario = (Long) searchModel.getFilter().get("uID");
    if (idUsuario != null) {
        crit.createAlias("assinadoPara", "assinadoPara");
        crit.add(Restrictions.eq("assinadoPara.id", idUsuario));
    }
    String nomeProjeto = null;
    // configura filtros das colunas da tabela, somente necessário se houver relacionamentos(ex:issue->projeto)
    // ou para alterar comportamento padrão dos filtros {@see StandaloneHenericHibernateDao#addBasicFilterRestrictions}
    Map<String, String> tableFilters = searchModel.getDatatableFilter();
    if (tableFilters != null && !tableFilters.isEmpty()) {
        String id = tableFilters.get("id");
        if (id != null && !"".endsWith(id)) {
            try {
                crit.add(Restrictions.eq("id", Long.parseLong(id)));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        nomeProjeto = tableFilters.get("projeto.nome");
        if (nomeProjeto != null) {
            crit.createAlias("projeto", "projeto");
            crit.add(Restrictions.ilike("projeto.nome", nomeProjeto, MatchMode.ANYWHERE));
        }
        String sumario = tableFilters.get("sumario");
        if (sumario != null) {
            crit.add(Restrictions.ilike("sumario", sumario, MatchMode.ANYWHERE));
        }
        String tipo = tableFilters.get("tipo");
        if (tipo != null) {
            if (TipoDeIssue.BUG.name().equals(tipo)) {
                crit.add(Restrictions.eq("tipo", TipoDeIssue.BUG));
            } else if (TipoDeIssue.FEATURE.name().equals(tipo)) {
                crit.add(Restrictions.eq("tipo", TipoDeIssue.FEATURE));
            }
        }
    }
    //cria join para ordenar por "assinadoPara"
    String sortField = searchModel.getSortField();
    if (//se idUsuario for != null é pq o alias ja foi criado
    sortField != null && sortField.equals("assinadoPara.nome") && idUsuario == null) {
        crit.createAlias("assinadoPara", "assinadoPara", JoinType.LEFT_OUTER_JOIN);
    }
    if (//se nome projeto != null é pq o alias ja foi criado
    sortField != null && sortField.equals("projeto.nome") && nomeProjeto == null) {
        crit.createAlias("projeto", "projeto", JoinType.LEFT_OUTER_JOIN);
    }
    return crit;
}
Example 7
Project: issuetracker-weld-master  File: IssueServiceImpl.java View source code
/**
	 * metodo invocado toda vez que uma lazy datatable de um MB(ex:  <p:datatable value="#{issueBean.dataModel}") que usa
	 * esta service for atualizada(via ajax ou não)
	 */
@Override
public Criteria configPagination(SearchModel<Issue> searchModel) {
    //configura paginação para o dashboard
    //parametro passado atraves do mapa de parametros {@see DashboardBean#preload()}
    Long idUsuario = (Long) searchModel.getFilter().get("uID");
    if (idUsuario != null) {
        crud.join("assinadoPara", "assinadoPara").eq("assinadoPara.id", idUsuario);
    }
    String nomeProjeto = null;
    // configura filtros das colunas da tabela, somente necessário se houver relacionamentos(ex:issue->projeto)
    // ou para alterar comportamento padrão dos filtros {@see StandaloneHenericHibernateDao#addBasicFilterRestrictions}
    Map<String, String> tableFilters = searchModel.getDatatableFilter();
    if (tableFilters != null && !tableFilters.isEmpty()) {
        String id = tableFilters.get("id");
        if (id != null && !"".endsWith(id)) {
            try {
                crud.eq("id", Long.parseLong(id));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        nomeProjeto = tableFilters.get("projeto.nome");
        if (nomeProjeto != null) {
            crud.join("projeto", "projeto");
            crud.ilike("projeto.nome", nomeProjeto, MatchMode.ANYWHERE);
        }
        String sumario = tableFilters.get("sumario");
        if (sumario != null) {
            crud.ilike("sumario", sumario, MatchMode.ANYWHERE);
        }
        String tipo = tableFilters.get("tipo");
        if (tipo != null) {
            if (TipoDeIssue.BUG.name().equals(tipo)) {
                crud.eq("tipo", TipoDeIssue.BUG);
            } else if (TipoDeIssue.FEATURE.name().equals(tipo)) {
                crud.eq("tipo", TipoDeIssue.FEATURE);
            }
        }
    }
    //cria join para ordenar por "assinadoPara"
    String sortField = searchModel.getSortField();
    if (//se idUsuario for != null é pq o alias ja foi criado
    sortField != null && sortField.equals("assinadoPara.nome") && idUsuario == null) {
        crud.join("assinadoPara", "assinadoPara", JoinType.LEFT_OUTER_JOIN);
    }
    if (//se nome projeto != null é pq o alias ja foi criado
    sortField != null && sortField.equals("projeto.nome") && nomeProjeto == null) {
        crud.join("projeto", "projeto", JoinType.LEFT_OUTER_JOIN);
    }
    return crud.getCriteria(true);
}
Example 8
Project: midpoint-master  File: RootHibernateQuery.java View source code
public Condition createLike(String propertyPath, String value, MatchMode matchMode, boolean ignoreCase) {
    switch(matchMode) {
        case ANYWHERE:
            value = "%" + value + "%";
            break;
        case START:
            value = value + "%";
            break;
        case END:
            value = "%" + value;
            break;
        default:
            throw new IllegalStateException("Unsupported match mode: " + matchMode);
    }
    return new SimpleComparisonCondition(this, propertyPath, value, "like", ignoreCase);
}
Example 9
Project: testcube-server-master  File: HibernateTestRunResult.java View source code
@Override
@SuppressWarnings("unchecked")
public List<ITestRunResult> findAll(Paging paging, Sorting sorting, String keyword, TestRun testRun, RunStatus status) {
    Criteria criteria = getCurrentSession().createCriteria(TestRunResult.class);
    if (keyword != null) {
        criteria.createAlias(TestRunResult.FIELD_TESTCASE, TestRunResult.FIELD_TESTCASE_ALIAS);
        if (StringUtils.isNotEmpty(keyword)) {
            criteria.add(Restrictions.or(Restrictions.ilike(TestRunResult.FIELD_TESTCASE_ALIAS + "." + TestCase.FIELD_NAME, keyword.toLowerCase(), MatchMode.ANYWHERE), Restrictions.ilike(TestRunResult.FIELD_TESTCASE_ALIAS + "." + TestCase.FIELD_DESC, keyword.toLowerCase(), MatchMode.ANYWHERE)));
        }
    }
    if (testRun != null) {
        criteria.add(Restrictions.eq(TestRunResult.FIELD_TEST_RUN, testRun));
    }
    if (status != null) {
        criteria.add(Restrictions.and(Restrictions.eq(TestRunResult.FIELD_STATUS, status)));
    }
    addPaging(criteria, paging);
    addSorting(criteria, sorting);
    return criteria.list();
}
Example 10
Project: titanic-javaee7-master  File: UsuarioRepositorio.java View source code
@SuppressWarnings("unchecked")
public List<Usuario> listarUsuariosFiltrados(UsuarioFiltros usuarioFiltros) {
    Session session = entityManager.unwrap(Session.class);
    Criteria criteria = session.createCriteria(Usuario.class);
    if (StringUtils.isNotBlank(usuarioFiltros.getEmail())) {
        criteria.add(Restrictions.eq("email", usuarioFiltros.getEmail()));
    }
    if (StringUtils.isNotBlank(usuarioFiltros.getNombre())) {
        criteria.add(Restrictions.ilike("nombreUsuario", usuarioFiltros.getNombre(), MatchMode.ANYWHERE));
    }
    return criteria.addOrder(Order.asc("nombreUsuario")).list();
}
Example 11
Project: Databinder-for-Wicket-master  File: SearchPanel.java View source code
/**
	 * Adds a criterion that will match the current search string within (depending on the MatchMode)
	 * any of the given properties. If the search is empty, no criterion is added.
	 * @param matchMode used against all properties
	 * @param searchProperty one or more properties to be searched
	 * @return builder to be used with list model or data provider
	 */
public CriteriaBuilder getCriteriaBuilder(final MatchMode matchMode, final String... searchProperty) {
    return new CriteriaBuilder() {

        public void build(final Criteria criteria) {
            final String search = (String) getDefaultModelObject();
            if (search != null) {
                final Disjunction d = Restrictions.disjunction();
                for (final String prop : searchProperty) {
                    d.add(Property.forName(prop).like(search, matchMode));
                }
                criteria.add(d);
            }
        }
    };
}
Example 12
Project: EngSoft2011_Grupo1-master  File: TurmaDao.java View source code
/**
	 * Cadastra a turma no banco de dados.
	 * 
	 * @param turma
	 */
@SuppressWarnings("unchecked")
public void salvaTurma(Turma turma) {
    String nome = turma.getNome();
    Disciplina disciplina = turma.getDisciplina();
    List<Turma> listaDeTurmas = session.createCriteria(Turma.class).add(Restrictions.like("nome", nome, MatchMode.EXACT)).add(Restrictions.eq("disciplina", disciplina)).list();
    if (listaDeTurmas.size() != 0)
        return;
    Transaction tx = session.beginTransaction();
    session.save(turma);
    tx.commit();
}
Example 13
Project: ismp_manager-master  File: SysLogSourceDaoImpl.java View source code
/**
	 * spliceCriteria decription : 带分页功能的多�件查询语�拼接
	 * @param sysLogSource
	 * @param pageNo
	 * @param pageRowNum
	 * @return
	 */
private Criteria spliceCriteria(SysLogSource sysLogSource, List<Domain> domain, Integer pageNo, Integer pageRowNum) {
    Criteria criteria = getSession().createCriteria(SysLogSource.class);
    if (sysLogSource != null) {
        // 产生范例对�
        Example example = Example.create(sysLogSource);
        // 排除属性为null
        // example.excludeNone();
        // 对String属性都用模糊匹�方�
        example.enableLike(MatchMode.ANYWHERE);
        criteria.add(example);
        if (domain.size() > 0)
            criteria.add(Expression.in("domain", domain));
        criteria.addOrder(Order.desc("createTime"));
        if (sysLogSource.getId() != null) {
            criteria.add(Expression.eq("id", sysLogSource.getId()));
        }
    }
    // 添加分页查询�件:起始页
    if (null != pageNo) {
        criteria.setFirstResult(pageNo.intValue());
    }
    // 添加分页查询�件:�页需�显示的数目
    if (null != pageRowNum) {
        criteria.setMaxResults(pageRowNum.intValue());
    }
    return criteria;
}
Example 14
Project: ListaExercicio-master  File: QuestaoDao.java View source code
private Criteria listaFiltrada(String filtro, Long idLista) {
    Criteria criteria = this.session.createCriteria(Questao.class);
    /**
		 * filtra por disciplina
		*/
    Disciplina disciplina = listaDeExercicioDao.carrega(idLista).getTurma().getDisciplina();
    criteria.createCriteria("disciplina").add(Restrictions.eq("id", disciplina.getId()));
    if (filtro != null && !filtro.equals(""))
        criteria.createCriteria("tags").add(Restrictions.ilike("nome", filtro, MatchMode.ANYWHERE));
    return criteria;
}
Example 15
Project: bbks-master  File: CommentService.java View source code
/**
	 * 
	 * @param type---评论类型�book:图书;user:用户动�;】
	 * @param contentId---原题目id�如,图书id】
	 * @param comment---not null 评论内容�】
	 * @return
	 */
public List<Comment> find(Comment comment) {
    DetachedCriteria dc = commentDao.createDetachedCriteria();
    if (StringUtils.isNotEmpty(comment.getModule())) {
        dc.add(Restrictions.eq("module", comment.getModule()));
    }
    if (comment.getContentId() != null) {
        dc.add(Restrictions.eq("contentId", comment.getContentId()));
    }
    if (comment.getUid() != null) {
        dc.add(Restrictions.eq("uid", comment.getUid()));
    }
    //评论人
    if (StringUtils.isNotBlank(comment.getName())) {
        dc.add(Restrictions.eq("name", comment.getName()));
    }
    //评论的标题
    if (StringUtils.isNotBlank(comment.getTitle())) {
        dc.add(Restrictions.like("title", comment.getTitle(), MatchMode.ANYWHERE));
    }
    dc.addOrder(Order.desc("createDate"));
    return commentDao.find(dc);
}
Example 16
Project: caratarse-auth-master  File: CriteriaFilterHelper.java View source code
@Override
public void filterOn(FilterComponent c) {
    switch(c.getOperator()) {
        case // String-related
        CONTAINS:
            crit.add(Restrictions.ilike(c.getField(), c.getValue().toString(), MatchMode.ANYWHERE));
            break;
        case // String-related
        STARTS_WITH:
            crit.add(Restrictions.ilike(c.getField(), c.getValue().toString(), MatchMode.START));
            break;
        case GREATER_THAN:
            crit.add(Restrictions.gt(c.getField(), c.getValue()));
            break;
        case GREATER_THAN_OR_EQUAL_TO:
            crit.add(Restrictions.ge(c.getField(), c.getValue()));
            break;
        case LESS_THAN:
            crit.add(Restrictions.lt(c.getField(), c.getValue()));
            break;
        case LESS_THAN_OR_EQUAL_TO:
            crit.add(Restrictions.le(c.getField(), c.getValue()));
            break;
        case NOT_EQUALS:
            crit.add(Restrictions.ne(c.getField(), c.getValue()));
            break;
        case EQUALS:
        default:
            crit.add(Restrictions.eq(c.getField(), c.getValue()));
            break;
    }
}
Example 17
Project: jpa-issuetracker-project-master  File: IssueDaoImpl.java View source code
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
@Override
public List<Issue> buscaPorSumario(String sumario) {
    Session session = getSession();
    Criteria criteria = session.createCriteria(Issue.class);
    criteria.add(Restrictions.ilike("sumario", sumario, MatchMode.ANYWHERE));
    // == FetchMode.LAZY
    criteria.setFetchMode("projeto", FetchMode.SELECT);
    criteria.setFetchMode("reportadoPor", FetchMode.SELECT);
    criteria.setFetchMode("assinadoPara", FetchMode.SELECT);
    return criteria.list();
}
Example 18
Project: libreplan-master  File: CostCategoryDAO.java View source code
@Override
@Transactional(readOnly = true)
public CostCategory findByNameCaseInsensitive(String name) throws InstanceNotFoundException {
    Criteria c = getSession().createCriteria(CostCategory.class);
    c.add(Restrictions.ilike("name", name, MatchMode.EXACT));
    CostCategory result = (CostCategory) c.uniqueResult();
    if (result == null) {
        throw new InstanceNotFoundException(name, getEntityClass().getName());
    }
    return result;
}
Example 19
Project: mateo-master  File: ActivoDaoHibernate.java View source code
@Override
@Transactional(readOnly = true)
public Map<String, Object> lista(Map<String, Object> params) {
    log.debug("Buscando lista de activos con params {}", params);
    if (params == null) {
        params = new HashMap<>();
    }
    if (!params.containsKey("max")) {
        params.put("max", 10);
    } else {
        params.put("max", Math.min((Integer) params.get("max"), 100));
    }
    if (params.containsKey("pagina")) {
        Long pagina = (Long) params.get("pagina");
        Long offset = (pagina - 1) * (Integer) params.get("max");
        params.put("offset", offset.intValue());
    }
    if (!params.containsKey("offset")) {
        params.put("offset", 0);
    }
    Criteria criteria = currentSession().createCriteria(Activo.class);
    Criteria countCriteria = currentSession().createCriteria(Activo.class);
    criteria.createAlias("tipoActivo", "ta");
    countCriteria.createAlias("tipoActivo", "ta");
    if (params.containsKey("empresa")) {
        criteria.createCriteria("empresa").add(Restrictions.idEq(params.get("empresa")));
        countCriteria.createCriteria("empresa").add(Restrictions.idEq(params.get("empresa")));
    }
    if (params.containsKey("tipoActivoIds")) {
        criteria.add(Restrictions.in("ta.id", (List) params.get("tipoActivoIds")));
        countCriteria.add(Restrictions.in("ta.id", (List) params.get("tipoActivoIds")));
    }
    if (params.containsKey("cuentaId")) {
        criteria.createCriteria("centroCosto").add(Restrictions.eq("id.idCosto", params.get("cuentaId")));
        countCriteria.createCriteria("centroCosto").add(Restrictions.eq("id.idCosto", params.get("cuentaId")));
    }
    if (params.containsKey("proveedorId")) {
        criteria.createCriteria("proveedor").add(Restrictions.idEq(params.get("proveedorId")));
        countCriteria.createCriteria("proveedor").add(Restrictions.idEq(params.get("proveedorId")));
    }
    Date fechaIniciado = null;
    if (params.containsKey("fechaIniciado")) {
        fechaIniciado = (Date) params.get("fechaIniciado");
        criteria.add(Restrictions.ge("fechaCompra", fechaIniciado));
        countCriteria.add(Restrictions.ge("fechaCompra", fechaIniciado));
    }
    Date fechaTerminado = null;
    if (params.containsKey("fechaTerminado")) {
        Calendar cal = Calendar.getInstance();
        cal.setTime((Date) params.get("fechaTerminado"));
        cal.set(Calendar.HOUR_OF_DAY, 23);
        cal.set(Calendar.MINUTE, 59);
        cal.set(Calendar.SECOND, 59);
        cal.set(Calendar.MILLISECOND, 999);
        fechaTerminado = cal.getTime();
        criteria.add(Restrictions.le("fechaCompra", fechaTerminado));
        countCriteria.add(Restrictions.le("fechaCompra", fechaTerminado));
    }
    if (params.containsKey("bajas")) {
        if (fechaIniciado != null) {
            criteria.add(Restrictions.eq("inactivo", true));
            countCriteria.add(Restrictions.eq("inactivo", true));
            criteria.add(Restrictions.ge("fechaInactivo", fechaIniciado));
            countCriteria.add(Restrictions.ge("fechaInactivo", fechaIniciado));
            if (fechaTerminado != null) {
                criteria.add(Restrictions.le("fechaInactivo", fechaTerminado));
                countCriteria.add(Restrictions.le("fechaInactivo", fechaTerminado));
            }
        } else if (fechaTerminado != null) {
            criteria.add(Restrictions.eq("inactivo", true));
            countCriteria.add(Restrictions.eq("inactivo", true));
            criteria.add(Restrictions.le("fechaInactivo", fechaTerminado));
            countCriteria.add(Restrictions.le("fechaInactivo", fechaTerminado));
        } else {
            criteria.add(Restrictions.eq("inactivo", true));
            countCriteria.add(Restrictions.eq("inactivo", true));
        }
    } else {
        criteria.add(Restrictions.eq("inactivo", false));
        countCriteria.add(Restrictions.eq("inactivo", false));
    }
    if (params.containsKey("reubicaciones")) {
        if (fechaIniciado != null) {
            criteria.add(Restrictions.isNotNull("fechaReubicado"));
            countCriteria.add(Restrictions.isNotNull("fechaReubicado"));
            criteria.add(Restrictions.ge("fechaReubicado", fechaIniciado));
            countCriteria.add(Restrictions.ge("fechaReubicado", fechaIniciado));
            if (fechaTerminado != null) {
                criteria.add(Restrictions.le("fechaReubicado", fechaIniciado));
                countCriteria.add(Restrictions.le("fechaReubicado", fechaIniciado));
            }
        } else if (fechaTerminado != null) {
            criteria.add(Restrictions.isNotNull("fechaReubicado"));
            countCriteria.add(Restrictions.isNotNull("fechaReubicado"));
            criteria.add(Restrictions.le("fechaReubicado", fechaIniciado));
            countCriteria.add(Restrictions.le("fechaReubicado", fechaIniciado));
        } else {
            criteria.add(Restrictions.isNotNull("fechaReubicado"));
            countCriteria.add(Restrictions.isNotNull("fechaReubicado"));
        }
    }
    if (params.containsKey("responsableNombre")) {
        criteria.add(Restrictions.ilike("responsable", (String) params.get("responsable"), MatchMode.ANYWHERE));
        countCriteria.add(Restrictions.ilike("responsable", (String) params.get("responsable"), MatchMode.ANYWHERE));
    }
    if (params.containsKey("filtro")) {
        String filtro = (String) params.get("filtro");
        Disjunction propiedades = Restrictions.disjunction();
        propiedades.add(Restrictions.ilike("folio", filtro, MatchMode.ANYWHERE));
        propiedades.add(Restrictions.ilike("procedencia", filtro, MatchMode.ANYWHERE));
        propiedades.add(Restrictions.ilike("factura", filtro, MatchMode.ANYWHERE));
        propiedades.add(Restrictions.ilike("pedimento", filtro, MatchMode.ANYWHERE));
        propiedades.add(Restrictions.ilike("poliza", filtro, MatchMode.ANYWHERE));
        propiedades.add(Restrictions.ilike("codigo", filtro, MatchMode.ANYWHERE));
        propiedades.add(Restrictions.ilike("descripcion", filtro, MatchMode.ANYWHERE));
        propiedades.add(Restrictions.ilike("marca", filtro, MatchMode.ANYWHERE));
        propiedades.add(Restrictions.ilike("modelo", filtro, MatchMode.ANYWHERE));
        propiedades.add(Restrictions.ilike("ubicacion", filtro, MatchMode.ANYWHERE));
        propiedades.add(Restrictions.ilike("responsable", filtro, MatchMode.ANYWHERE));
        criteria.add(propiedades);
        countCriteria.add(propiedades);
    }
    if (params.containsKey("order")) {
        criteria.addOrder(Order.asc("ta.cuenta.id.idCtaMayor"));
        String campo = (String) params.get("order");
        if (params.get("sort").equals("desc")) {
            criteria.addOrder(Order.desc(campo));
        } else {
            criteria.addOrder(Order.asc(campo));
        }
    } else {
        criteria.addOrder(Order.asc("ta.cuenta.id.idCtaMayor"));
        criteria.addOrder(Order.desc("folio"));
    }
    if (!params.containsKey("reporte")) {
        criteria.setFirstResult((Integer) params.get("offset"));
        criteria.setMaxResults((Integer) params.get("max"));
    }
    params.put("activos", criteria.list());
    countCriteria.setProjection(Projections.rowCount());
    params.put("cantidad", (Long) countCriteria.list().get(0));
    ProjectionList list = Projections.projectionList();
    list.add(Projections.sum("depreciacionAnual"), "depreciacionAnual");
    list.add(Projections.sum("depreciacionMensual"), "depreciacionMensual");
    list.add(Projections.sum("depreciacionAcumulada"), "depreciacionAcumulada");
    list.add(Projections.sum("moi"), "moi");
    list.add(Projections.groupProperty("fechaDepreciacion"), "fechaDepreciacion");
    countCriteria.setProjection(list);
    List<?> proyecciones = countCriteria.list();
    Iterator<?> iterator = proyecciones.iterator();
    if (iterator.hasNext()) {
        Object[] obj = (Object[]) iterator.next();
        NumberFormat nf = DecimalFormat.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
        Date fecha;
        if (obj[4] != null) {
            fecha = (Date) obj[4];
        } else {
            fecha = new Date();
        }
        params.put("resumen", new String[] { nf.format(obj[0]), nf.format(obj[1]), nf.format(obj[2]), nf.format(obj[3]), sdf.format(fecha) });
    }
    return params;
}
Example 20
Project: OpenHMIS-master  File: CashPointServiceImpl.java View source code
@Override
public List<CashPoint> getCashPointsByLocationAndName(final Location location, final String name, final boolean includeRetired, PagingInfo pagingInfo) {
    if (location == null) {
        throw new IllegalArgumentException("The location must be defined");
    }
    if (StringUtils.isEmpty(name)) {
        throw new IllegalArgumentException("The Cashpoint name must be defined.");
    }
    if (name.length() > MAX_CASHPOINT_NAME_CHARACTERS) {
        throw new IllegalArgumentException("The Cashpoint name must be less than 256 characters.");
    }
    return executeCriteria(CashPoint.class, pagingInfo, new Action1<Criteria>() {

        @Override
        public void apply(Criteria criteria) {
            criteria.add(Restrictions.eq(HibernateCriteriaConstants.LOCATION, location)).add(Restrictions.ilike(HibernateCriteriaConstants.NAME, name, MatchMode.START));
            if (!includeRetired) {
                criteria.add(Restrictions.eq(HibernateCriteriaConstants.RETIRED, false));
            }
        }
    });
}
Example 21
Project: openmrs-core-master  File: HibernateConceptDAO.java View source code
/**
	 * @see org.openmrs.api.db.ConceptDAO#getConceptReferenceTermByName(java.lang.String,
	 *      org.openmrs.ConceptSource)
	 */
@SuppressWarnings("rawtypes")
@Override
public ConceptReferenceTerm getConceptReferenceTermByName(String name, ConceptSource conceptSource) throws DAOException {
    Criteria criteria = sessionFactory.getCurrentSession().createCriteria(ConceptReferenceTerm.class);
    criteria.add(Restrictions.ilike("name", name, MatchMode.EXACT));
    criteria.add(Restrictions.eq("conceptSource", conceptSource));
    List terms = criteria.list();
    if (terms.isEmpty()) {
        return null;
    } else if (terms.size() > 1) {
        throw new APIException("ConceptReferenceTerm.foundMultipleTermsWithNameInSource", new Object[] { name, conceptSource.getName() });
    }
    return (ConceptReferenceTerm) terms.get(0);
}
Example 22
Project: openmrs-module-openhmis.cashier-master  File: CashPointServiceImpl.java View source code
@Override
public List<CashPoint> getCashPointsByLocationAndName(final Location location, final String name, final boolean includeRetired, PagingInfo pagingInfo) {
    if (location == null) {
        throw new IllegalArgumentException("The location must be defined");
    }
    if (StringUtils.isEmpty(name)) {
        throw new IllegalArgumentException("The Cashpoint name must be defined.");
    }
    if (name.length() > MAX_CASHPOINT_NAME_CHARACTERS) {
        throw new IllegalArgumentException("The Cashpoint name must be less than 256 characters.");
    }
    return executeCriteria(CashPoint.class, pagingInfo, new Action1<Criteria>() {

        @Override
        public void apply(Criteria criteria) {
            criteria.add(Restrictions.eq(HibernateCriteriaConstants.LOCATION, location)).add(Restrictions.ilike(HibernateCriteriaConstants.NAME, name, MatchMode.START));
            if (!includeRetired) {
                criteria.add(Restrictions.eq(HibernateCriteriaConstants.RETIRED, false));
            }
        }
    });
}
Example 23
Project: radiology-master  File: HibernateMrrtReportTemplateDAO.java View source code
/**
     * @see org.openmrs.module.radiology.report.template.MrrtReportTemplateService#getMrrtReportTemplates(MrrtReportTemplateSearchCriteria)
     */
@SuppressWarnings("unchecked")
@Override
public List<MrrtReportTemplate> getMrrtReportTemplates(MrrtReportTemplateSearchCriteria searchCriteria) {
    final Criteria crit = sessionFactory.getCurrentSession().createCriteria(MrrtReportTemplate.class);
    crit.addOrder(Order.asc("dcTermsTitle"));
    if (searchCriteria.getTitle() != null) {
        crit.add(Restrictions.ilike("dcTermsTitle", searchCriteria.getTitle() + "%", MatchMode.ANYWHERE));
    }
    if (searchCriteria.getPublisher() != null) {
        crit.add(Restrictions.ilike("dcTermsPublisher", searchCriteria.getPublisher() + "%", MatchMode.ANYWHERE));
    }
    if (searchCriteria.getLicense() != null) {
        crit.add(Restrictions.ilike("dcTermsLicense", searchCriteria.getLicense() + "%", MatchMode.ANYWHERE));
    }
    if (searchCriteria.getCreator() != null) {
        crit.add(Restrictions.ilike("dcTermsCreator", searchCriteria.getCreator() + "%", MatchMode.ANYWHERE));
    }
    final List<MrrtReportTemplate> result = (List<MrrtReportTemplate>) crit.list();
    return result == null ? new ArrayList<>() : result;
}
Example 24
Project: tourismwork-master  File: EmployeeDaoImpl.java View source code
@SuppressWarnings("unchecked")
public List<Employee> getEmployees(int groupId, String userName) {
    DetachedCriteria criteria = DetachedCriteria.forClass(Employee.class);
    if (groupId != 0)
        criteria.add(Restrictions.eq("group.groupId", groupId));
    if (StringUtil.hasLength(userName))
        criteria.add(Restrictions.like("userName", userName.trim(), MatchMode.ANYWHERE));
    criteria.addOrder(Order.asc("userCd"));
    criteria.setResultTransformer(CriteriaSpecification.ROOT_ENTITY);
    return getHibernateTemplate().findByCriteria(criteria);
}
Example 25
Project: wicket-web-beans-master  File: DataSearchFilter.java View source code
@Override
public void build(Criteria criteria) {
    super.build(criteria);
    if (searchPanel.getDefaultModelObject() != null && properties != null) {
        for (String alias : aliases) {
            criteria.createAlias(alias, alias);
        }
        Disjunction disjunction = Restrictions.disjunction();
        criteria.add(disjunction);
        for (String property : properties) {
            disjunction.add(Restrictions.ilike(property, searchPanel.getDefaultModelObject().toString(), MatchMode.ANYWHERE));
        }
    }
}
Example 26
Project: eGov-master  File: WorkProgressRegisterService.java View source code
@Transactional
public List<WorkProgressRegister> searchWorkProgressRegister(final WorkProgressRegisterSearchRequest workProgressRegisterSearchRequest) {
    if (workProgressRegisterSearchRequest != null) {
        final Criteria criteria = entityManager.unwrap(Session.class).createCriteria(WorkProgressRegister.class);
        if (workProgressRegisterSearchRequest.getDepartment() != null)
            criteria.add(Restrictions.eq("department.id", workProgressRegisterSearchRequest.getDepartment()));
        if (workProgressRegisterSearchRequest.getWorkIdentificationNumber() != null)
            criteria.add(Restrictions.eq("winCode", workProgressRegisterSearchRequest.getWorkIdentificationNumber()).ignoreCase());
        if (workProgressRegisterSearchRequest.getContractor() != null) {
            criteria.createAlias("contractor", "contractor");
            criteria.add(Restrictions.or(Restrictions.ilike("contractor.code", workProgressRegisterSearchRequest.getContractor(), MatchMode.ANYWHERE), Restrictions.ilike("contractor.name", workProgressRegisterSearchRequest.getContractor(), MatchMode.ANYWHERE)));
        }
        if (workProgressRegisterSearchRequest.getAdminSanctionFromDate() != null)
            criteria.add(Restrictions.ge("adminSanctionDate", workProgressRegisterSearchRequest.getAdminSanctionFromDate()));
        if (workProgressRegisterSearchRequest.getAdminSanctionToDate() != null)
            criteria.add(Restrictions.le("adminSanctionDate", workProgressRegisterSearchRequest.getAdminSanctionToDate()));
        if (workProgressRegisterSearchRequest.isSpillOverFlag())
            criteria.add(Restrictions.eq("spillOverFlag", workProgressRegisterSearchRequest.isSpillOverFlag()));
        criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
        return criteria.list();
    } else
        return new ArrayList<WorkProgressRegister>();
}
Example 27
Project: frontlinesms-core-master  File: HibernateGroupDao.java View source code
/** @see GroupDao#deleteGroup(Group, boolean) */
@Transactional
public void deleteGroup(Group group, boolean destroyContacts) {
    // Dereference all keywordActions relating to this group
    String keywordActionQuery = "DELETE FROM KeywordAction WHERE group_path=?";
    super.getHibernateTemplate().bulkUpdate(keywordActionQuery, group.getPath());
    Object[] paramValues = getPathParamValues(group);
    if (destroyContacts) {
        // If the contacts must also be destroyed, we start by selecting them
        String queryString = "SELECT DISTINCT contact FROM GroupMembership WHERE group_path=? OR group_path LIKE ?";
        List<Contact> contactsList = getList(Contact.class, queryString, paramValues);
        // Then we delete all group memberships for the group and its descendants
        String groupMembershipQuery = "DELETE from GroupMembership WHERE group_path=? OR group_path LIKE ?";
        super.getHibernateTemplate().bulkUpdate(groupMembershipQuery, paramValues);
        // Then, for each contact...
        for (Contact c : contactsList) {
            // We remove it from each group it's included in
            groupMembershipQuery = "DELETE from GroupMembership WHERE contact=?";
            super.getHibernateTemplate().bulkUpdate(groupMembershipQuery, c);
            // And we delete the contact
            String deleteContactQuery = "DELETE FROM Contact WHERE id=?";
            super.getHibernateTemplate().bulkUpdate(deleteContactQuery, c.getId());
        }
    } else {
        // We just delete all group memberships for the group and its descendants
        String groupMembershipQuery = "DELETE from GroupMembership WHERE group_path=? OR group_path LIKE ?";
        super.getHibernateTemplate().bulkUpdate(groupMembershipQuery, paramValues);
    }
    // Finally, we delete all child groups and the group itself
    DetachedCriteria criteria = super.getCriterion();
    Criterion equals = Restrictions.eq(Group.Field.PATH.getFieldName(), paramValues[0]);
    Criterion like = Restrictions.like(Group.Field.PATH.getFieldName(), paramValues[1].toString(), MatchMode.START);
    criteria.add(Restrictions.or(equals, like));
    List<Group> groups = getList(criteria);
    for (Group deletedGroup : groups) {
        this.delete(deletedGroup);
    }
}
Example 28
Project: FrontlineSMS-Forms-master  File: HibernateFormDao.java View source code
public void dereferenceGroup(Group group) {
    DetachedCriteria criteria = super.getCriterion();
    Criterion equals = Restrictions.eq(Form.FIELD_PERMITTED, group);
    Criterion like = Restrictions.like("permittedGroup.path", group.getPath() + Group.PATH_SEPARATOR, MatchMode.START);
    criteria.add(Restrictions.or(equals, like));
    List<Form> forms = getList(criteria);
    for (Form formWithDereferencedGroup : forms) {
        System.err.println("Delete form: " + formWithDereferencedGroup.getName());
        formWithDereferencedGroup.setPermittedGroup(null);
        try {
            this.update(formWithDereferencedGroup);
        } catch (DuplicateKeyException e) {
            throw new RuntimeException("There was a problem removing the deleted group from its attached form.");
        }
    }
}
Example 29
Project: frontlinesms-plugin-forms-master  File: HibernateFormDao.java View source code
public void dereferenceGroup(Group group) {
    DetachedCriteria criteria = super.getCriterion();
    Criterion equals = Restrictions.eq(Form.FIELD_PERMITTED, group);
    Criterion like = Restrictions.like("permittedGroup.path", group.getPath() + Group.PATH_SEPARATOR, MatchMode.START);
    criteria.add(Restrictions.or(equals, like));
    List<Form> forms = getList(criteria);
    for (Form formWithDereferencedGroup : forms) {
        formWithDereferencedGroup.setPermittedGroup(null);
        try {
            this.update(formWithDereferencedGroup);
        } catch (DuplicateKeyException e) {
            throw new RuntimeException("There was a problem removing the deleted group from its attached form.");
        }
    }
}
Example 30
Project: lemo2-master  File: ServiceCourseTitleSearch.java View source code
/**
	 * Gets the details of all courses whose title matches search text. Informations include id, title, description, 
	 * number of participants, time of first student-request, time of latest student-request.
	 * 
	 * @param text	.
	 * 
	 * @return	A List of CourseObjects containing the information.
	 */
@GET
public ResultListCourseObject getCoursesByText(@QueryParam(MetaParam.SEARCH_TEXT) final String text, @QueryParam(MetaParam.RESULT_AMOUNT) final Long count, @QueryParam(MetaParam.OFFSET) final Long offset) {
    IDBHandler dbHandler = ServerConfiguration.getInstance().getMiningDbHandler();
    List<CourseObject> result = new ArrayList<CourseObject>();
    result.add(new CourseObject());
    result.add(new CourseObject());
    if (text == null || text.equals("")) {
        return new ResultListCourseObject(result);
    }
    // Set up db-connection
    final Session session = dbHandler.getMiningSession();
    Criteria criteria = session.createCriteria(CourseMining.class, "course");
    criteria.add(Restrictions.ilike("course.title", text, MatchMode.ANYWHERE));
    @SuppressWarnings("unchecked") final ArrayList<CourseMining> courses = (ArrayList<CourseMining>) criteria.list();
    List<Long> ids = new ArrayList<Long>();
    for (CourseMining course : courses) {
        ids.add(course.getId());
    }
    Map<Long, Long> userMap = StudentHelper.getCourseStudentsAliasKeys(ids, new ArrayList<Long>());
    for (CourseMining courseMining : courses) {
        criteria = session.createCriteria(ILogMining.class, "log");
        criteria.add(Restrictions.eq("log.course.id", courseMining.getId()));
        if (userMap.size() > 0) {
            criteria.add(Restrictions.in("log.user.id", userMap.values()));
        }
        @SuppressWarnings("unchecked") ArrayList<ILogMining> logs = (ArrayList<ILogMining>) criteria.list();
        Collections.sort(logs);
        Long lastTime = 0L;
        Long firstTime = 0L;
        if (logs.size() > 0) {
            lastTime = logs.get(logs.size() - 1).getTimestamp();
            firstTime = logs.get(0).getTimestamp();
        }
        ServiceCourseDetails scd = new ServiceCourseDetails();
        final CourseObject co = new CourseObject(courseMining.getId(), courseMining.getShortname(), courseMining.getTitle(), userMap.size(), lastTime, firstTime, scd.getCourseHash(courseMining.getId()), StudentHelper.getGenderSupport(courseMining.getId()));
        result.add(co);
    }
    if (count != null && count > 0) {
        if (offset != null && offset > 0) {
            if (result.size() - offset >= count) {
                result = result.subList(offset.intValue(), offset.intValue() + count.intValue());
            } else {
                result = result.subList(offset.intValue(), courses.size() - 1);
            }
        } else {
            if (result.size() > count) {
                result = result.subList(0, count.intValue());
            }
        }
    }
    session.close();
    return new ResultListCourseObject(result);
}
Example 31
Project: MavenOneCMDB-master  File: HibernateDao.java View source code
public QueryResult<ICi> query(QueryCriteria criteria, boolean count) {
    DetachedCriteria hibCiCriteria = DetachedCriteria.forClass(ConfigurationItem.class);
    DetachedCriteria hibAttributeCriteria = DetachedCriteria.forClass(BasicAttribute.class);
    // Search in the db...
    if (criteria.getOffspringOfId() != null) {
        try {
            // Query for an unique id.
            Long longId = Long.parseLong(criteria.getOffspringOfId());
            hibCiCriteria.add(Expression.eq("derivedFromId", longId));
        } catch (NumberFormatException e) {
            log.warn("QueryCriteria contained not a long offspringId <" + criteria.getCiId());
            throw new IllegalArgumentException("Not a correct long ci id <" + criteria.getCiId());
        }
    } else if (criteria.getOffspringOfAlias() != null) {
        ICi ci = findCiByAlias(new Path<String>(criteria.getOffspringOfAlias()));
        if (criteria.getOffspringDepth() != null) {
            if (ci == null) {
                // Is an error, but we don't throw an exception, instead it will return empty/0 
                DetachedCriteria hibAliasCiCriteria = DetachedCriteria.forClass(ConfigurationItem.class);
                hibAliasCiCriteria.add(Expression.eq("alias", criteria.getOffspringOfAlias()));
                DetachedCriteria idCriteria = hibAliasCiCriteria.setProjection(Projections.property("longId"));
                hibCiCriteria.add(Property.forName("derivedFromId").in(idCriteria));
            } else {
                // TODO: append %/%/% according to offspring depth. 
                hibCiCriteria.add(Expression.ilike("templatePath", ci.getTemplatePath() + "/%"));
            }
        } else {
            if (ci != null) {
                hibCiCriteria.add(Expression.eq("derivedFromId", ci.getId().asLong()));
            } else {
                hibCiCriteria.add(Expression.eq("derivedFromId", new Long(0)));
            }
        }
    //hibAttributeCriteria.add(Expression.eq("alias", criteria.getOffspringOfAlias()));
    }
    if (criteria.getCiAlias() != null) {
        hibCiCriteria.add(Expression.eq("alias", criteria.getCiAlias()));
    } else if (criteria.getCiId() != null) {
        try {
            // Query for an unique id.
            Long longId = Long.parseLong(criteria.getCiId());
            hibCiCriteria.add(Expression.eq("longId", longId));
        } catch (NumberFormatException e) {
            log.warn("QueryCriteria contained not a long ci id <" + criteria.getCiId());
            throw new IllegalArgumentException("Not a correct long ci id <" + criteria.getCiId());
        }
    /*
			if (ci == null || ci instanceof IAttribute) {
				if (count) {
					result.setTotalHits(0);
				} 
			} else {
				if (count) {
					result.setTotalHits(1);
				}
				result.add(ci);
			}
			return(result);
			*/
    }
    if (criteria.getMatchType() != null) {
        ICi type = findCiByAlias(new Path<String>(criteria.getMatchType()));
        if (type != null) {
            Disjunction orAttribute = Restrictions.disjunction();
            String path = type.getTemplatePath();
            String paths[] = path.split("/");
            if (paths.length > 1) {
                for (int i = 1; i < paths.length; i++) {
                    orAttribute.add(Expression.ilike("typeName", "%#" + paths[i], MatchMode.START));
                }
                DetachedCriteria typeCrit = DetachedCriteria.forClass(BasicAttribute.class);
                typeCrit.add(Expression.isNull("derivedFromId"));
                typeCrit.add(orAttribute);
                DetachedCriteria idCrit = typeCrit.setProjection(Projections.property("ownerId"));
                hibCiCriteria.add(Property.forName("longId").in(idCrit));
                if (criteria.getMatchCiPath() != null) {
                    String idPath = "";
                    String ciPath[] = criteria.getMatchCiPath().split("/");
                    if (ciPath.length > 0) {
                        for (int i = 0; i < ciPath.length; i++) {
                            ICi ci = findCiByAlias(new Path<String>(ciPath[i]));
                            if (ci != null) {
                                idPath += "/" + ci.getId().asLong();
                            }
                        }
                        // TODO: append %/%/% according to offspring depth. 
                        hibCiCriteria.add(Expression.ilike("templatePath", idPath + "/%"));
                    }
                }
            }
        }
    }
    if (criteria.isMatchCiTemplates() && criteria.isMatchCiInstances()) {
    // Search Both.
    } else if (criteria.isMatchCiTemplates()) {
        hibCiCriteria.add(Expression.eq("isBlueprint", Boolean.TRUE));
    } else if (criteria.isMatchCiInstances()) {
        hibCiCriteria.add(Expression.eq("isBlueprint", Boolean.FALSE));
    }
    if (criteria.isMatchAttributeTemplates() && criteria.isMatchAttributeInstances()) {
    // Search both
    } else if (criteria.isMatchAttributeTemplates()) {
        hibAttributeCriteria.add(Expression.eq("isBlueprint", Boolean.TRUE));
    } else if (criteria.isMatchAttributeInstances()) {
        hibAttributeCriteria.add(Expression.eq("isBlueprint", Boolean.FALSE));
    }
    if (criteria.getText() != null) {
        Disjunction orAttribute = Restrictions.disjunction();
        Disjunction orCi = Restrictions.disjunction();
        boolean orAttributeAdded = false;
        boolean orCiAdded = false;
        if (criteria.isTextMatchAlias()) {
            orCi.add(Expression.ilike("alias", criteria.getText(), MatchMode.ANYWHERE));
            orAttribute.add(Expression.ilike("alias", criteria.getText(), MatchMode.ANYWHERE));
            orAttributeAdded = true;
            orCiAdded = true;
        }
        if (criteria.isTextMatchDescription()) {
            orCi.add(Expression.ilike("description", criteria.getText(), MatchMode.ANYWHERE));
            orAttribute.add(Expression.ilike("description", criteria.getText(), MatchMode.ANYWHERE));
            orAttributeAdded = true;
            orCiAdded = true;
        }
        if (criteria.isTextMatchValue()) {
            orAttribute.add(Expression.ilike("valueAsString", criteria.getText(), MatchMode.ANYWHERE));
            orAttributeAdded = true;
            // Enable Attribute serach....
            criteria.setMatchAttribute(true);
        }
        if (orAttributeAdded) {
            if (criteria.getMatchAttributeAlias() != null) {
                hibAttributeCriteria.add(Expression.eq("alias", criteria.getMatchAttributeAlias()));
            }
            hibAttributeCriteria.add(orAttribute);
            DetachedCriteria idCriteria = hibAttributeCriteria.setProjection(Projections.property("ownerId"));
            orCi.add(Property.forName("longId").in(idCriteria));
            orCiAdded = true;
        }
        if (orCiAdded) {
            hibCiCriteria.add(orCi);
        }
    }
    QueryResult<ICi> result = new QueryResult<ICi>();
    /*
		if (criteria.isMatchAttribute()) {
			DetachedCriteria idCriteria = hibAttributeCriteria.setProjection(Projections.property("ownerId"));
			hibCiCriteria.add(Property.forName("longId").in(idCriteria));
		}
		*/
    // Search ICi.
    Session session = getSession();
    try {
        Profiler.start("QueryCi():");
        if (count) {
            Criteria hibCriteria = hibCiCriteria.getExecutableCriteria(session);
            hibCriteria.setProjection(Projections.rowCount());
            List list = hibCriteria.list();
            if (list != null && !list.isEmpty()) {
                Integer itemCount = ((Integer) list.get(0)).intValue();
                result.setTotalHits(itemCount);
            }
        } else {
            if (criteria.getOrderAttAlias() != null) {
                DetachedCriteria idCriteria = hibCiCriteria.setProjection(Projections.property("longId"));
                DetachedCriteria attr = DetachedCriteria.forClass(BasicAttribute.class);
                attr.add(Expression.eq("alias", criteria.getOrderAttAlias()));
                attr.add(Property.forName("ownerId").in(idCriteria));
                if (criteria.isOrderAscending()) {
                    attr.addOrder(Order.asc(criteria.getOrderType()));
                } else {
                    attr.addOrder(Order.desc(criteria.getOrderType()));
                }
                Criteria attrCriteria = attr.getExecutableCriteria(session);
                if (criteria.getMaxResult() != null) {
                    attrCriteria.setMaxResults(criteria.getMaxResult());
                }
                if (criteria.getFirstResult() != null) {
                    attrCriteria.setFirstResult(criteria.getFirstResult());
                }
                List<IAttribute> attrs = attrCriteria.list();
                for (IAttribute a : attrs) {
                    result.add(a.getOwner());
                }
            } else {
                hibCiCriteria.addOrder(Order.asc("alias"));
                Criteria hibCriteria = hibCiCriteria.getExecutableCriteria(session);
                if (criteria.getMaxResult() != null) {
                    hibCriteria.setMaxResults(criteria.getMaxResult());
                }
                if (criteria.getFirstResult() != null) {
                    hibCriteria.setFirstResult(criteria.getFirstResult());
                }
                List objects = hibCriteria.list();
                result.addAll(objects);
            }
        }
    } finally {
        Profiler.stop();
        closeSession(session);
    }
    return (result);
}
Example 32
Project: openmrs-module-webservices.rest-master  File: RestHelperServiceImpl.java View source code
@Override
public List<Patient> findPatientsByIdentifierStartingWith(String identifier, boolean includeAll) {
    Criteria criteria = getSession().createCriteria(Patient.class);
    criteria.createAlias("identifiers", "identifiers");
    criteria.add(Restrictions.like("identifiers.identifier", identifier, MatchMode.START));
    criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
    if (!includeAll) {
        criteria.add(Restrictions.eq("voided", false));
    }
    return criteria.list();
}
Example 33
Project: sample-boot-hibernate-master  File: OrmCriteria.java View source code
/** like�件を付与���。[複数フィールド�対�るOR��](値�null�時�無視�れ��) */
public OrmCriteria<T> like(String[] fields, String value, MatchMode mode) {
    if (isValid(value)) {
        Predicate[] predicates = new Predicate[fields.length];
        for (int i = 0; i < fields.length; i++) {
            predicates[i] = builder.like(root.get(fields[i]), mode.toMatchString(value));
        }
        add(builder.or(predicates));
    }
    return this;
}
Example 34
Project: seam-2.2-master  File: UserDAO.java View source code
private Criteria prepareExampleCriteria(User exampleUser, String orderByProperty, boolean orderDescending, String... ignoreProperty) {
    Example example = Example.create(exampleUser).enableLike(MatchMode.ANYWHERE).ignoreCase();
    // Sanitize input
    if (orderByProperty != null) {
        orderByProperty = orderByProperty.replaceAll("[^a-zA-Z0-9]", "");
    }
    for (String s : ignoreProperty) example.excludeProperty(s);
    Session session = (Session) entityManager.getDelegate();
    Criteria crit = session.createCriteria(User.class).add(example);
    if (orderByProperty != null)
        crit.addOrder(orderDescending ? Order.desc(orderByProperty) : Order.asc(orderByProperty));
    return crit.setResultTransformer(DistinctRootEntityResultTransformer.INSTANCE);
}
Example 35
Project: seam2jsf2-master  File: UserDAO.java View source code
private Criteria prepareExampleCriteria(User exampleUser, String orderByProperty, boolean orderDescending, String... ignoreProperty) {
    Example example = Example.create(exampleUser).enableLike(MatchMode.ANYWHERE).ignoreCase();
    // Sanitize input
    if (orderByProperty != null) {
        orderByProperty = orderByProperty.replaceAll("[^a-zA-Z0-9]", "");
    }
    for (String s : ignoreProperty) example.excludeProperty(s);
    Session session = (Session) entityManager.getDelegate();
    Criteria crit = session.createCriteria(User.class).add(example);
    if (orderByProperty != null)
        crit.addOrder(orderDescending ? Order.desc(orderByProperty) : Order.asc(orderByProperty));
    return crit.setResultTransformer(DistinctRootEntityResultTransformer.INSTANCE);
}
Example 36
Project: socialsite-master  File: AbstractDaoImpl.java View source code
/**
	 * helper method to find the count of item that match the filter
	 * 
	 * @param filter
	 *            filter text
	 * @param clazz
	 *            class of the item
	 * @param field
	 *            field that will be matched with the criteria
	 * @return
	 */
@SuppressWarnings("unchecked")
protected int count(String filter, final Class clazz, final String field) {
    // Avoids NPE
    filter = filter == null ? "" : filter;
    final Criteria criteria = getSession().createCriteria(clazz);
    criteria.add(Restrictions.ilike(field, filter, MatchMode.ANYWHERE));
    criteria.setProjection(Projections.rowCount());
    return (Integer) criteria.uniqueResult();
}
Example 37
Project: aperte-workflow-core-master  File: UserSearchForm.java View source code
@Override
public void configure(DetachedCriteria criteria) {
    if (hasText(email)) {
        criteria.add(Restrictions.ilike("email", email, MatchMode.ANYWHERE));
    }
    if (hasText(name)) {
        criteria.add(Restrictions.ilike("name", name, MatchMode.ANYWHERE));
    }
    if (hasText(surname)) {
        criteria.add(Restrictions.ilike("surname", surname, MatchMode.ANYWHERE));
    }
    if (hasText(companyId)) {
        criteria.createCriteria("attributes").add(Restrictions.eq("key", "teta_company")).add(Restrictions.ilike("value", companyId, MatchMode.ANYWHERE));
    } else // to trochę nie ma sensu: musimy zrobić multijoina po atrybutach
    if (hasText(mpkId)) {
        criteria.createCriteria("attributes").add(Restrictions.eq("key", "teta_mpk")).add(Restrictions.ilike("value", mpkId, MatchMode.ANYWHERE));
    }
    criteria.addOrder(Order.asc("login"));
    criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
}
Example 38
Project: BBS-master  File: PostDaoImpl.java View source code
public List<Post> search(String keyword) {
    Session session = getSession();
    String sql = "from Post post where post.title like ?";
    Query query = session.createQuery(sql);
    query.setString(0, '%' + keyword + '%');
    List list = query.list();
    session.flush();
    session.close();
    return list;
//		Session session = getSession();
//		Criteria criteria = session.createCriteria(Post.class);
//		criteria.add(Restrictions.like("title",keyword,MatchMode.ANYWHERE));
//		List list = criteria.list();
//		session.close();
//		return list;
}
Example 39
Project: cms-ce-master  File: GroupEntityDao.java View source code
public Object doInHibernate(Session session) throws HibernateException, SQLException {
    Criteria crit = session.createCriteria(GroupEntity.class).setCacheable(true);
    if (spec.getUserStoreKey() != null) {
        crit.add(Restrictions.eq("userStore.key", spec.getUserStoreKey().toInt()));
    } else if (spec.isGlobalOnly()) {
        crit.add(Restrictions.isNull("userStore.key"));
    }
    if (!spec.isIncludeDeleted()) {
        crit.add(Restrictions.eq("deleted", 0));
    }
    if (spec.getQuery() != null && spec.getQuery().length() > 0) {
        crit.add(Restrictions.ilike("name", spec.getQuery(), MatchMode.ANYWHERE));
    }
    if (spec.getOrderBy() != null && !spec.getOrderBy().equals("")) {
        if (spec.isOrderAscending()) {
            crit.addOrder(Order.asc(spec.getOrderBy()).ignoreCase());
        } else {
            crit.addOrder(Order.desc(spec.getOrderBy()).ignoreCase());
        }
    }
    if (spec.getGroupTypes() != null) {
        Collection<GroupType> gt = new ArrayList<GroupType>(spec.getGroupTypes());
        if (spec.isIncludeBuiltInGroups()) {
            if (!spec.isIncludeAnonymousGroups()) {
                gt.remove(GroupType.ANONYMOUS);
            }
        } else {
            gt.removeAll(GroupType.getBuiltInTypes());
        }
        if (spec.isIncludeUserGroups()) {
            gt.add(GroupType.USER);
        }
        crit.add(Restrictions.in("type", GroupType.getIntegerValues(gt)));
    } else {
        Collection<GroupType> notGroupType = new ArrayList<GroupType>();
        if (!spec.isIncludeBuiltInGroups()) {
            notGroupType.addAll(GroupType.getBuiltInTypes());
            if (spec.isIncludeAnonymousGroups()) {
                notGroupType.remove(GroupType.ANONYMOUS);
            }
        }
        if (!spec.isIncludeUserGroups()) {
            notGroupType.add(GroupType.USER);
        }
        if (!spec.isIncludeAnonymousGroups() && !notGroupType.contains(GroupType.ANONYMOUS)) {
            notGroupType.add(GroupType.ANONYMOUS);
        }
        crit.add(Restrictions.not(Restrictions.in("type", GroupType.getIntegerValues(notGroupType))));
    }
    crit.setFirstResult(spec.getIndex());
    List list = crit.list();
    if (spec.getCount() == null) {
        return list;
    } else {
        return list.subList(0, Math.min(spec.getCount(), list.size()));
    }
}
Example 40
Project: cryson-master  File: CrysonRepository.java View source code
@PostFilter("hasPermission(filterObject, 'read')")
public List findByExample(String entityClassName, Object exampleEntity, Set<String> associationsToFetch) {
    Criteria criteria = sessionFactory.getCurrentSession().createCriteria(entityClassName).add(Example.create(exampleEntity).enableLike(MatchMode.EXACT)).setResultTransformer(DistinctRootEntityResultTransformer.INSTANCE).setCacheable(true);
    setFetchModeForAssociations(criteria, associationsToFetch);
    return criteria.list();
}
Example 41
Project: eurocarbdb-master  File: SearchGlycanSequence.java View source code
private DetachedCriteria createSerializableCriteria() {
    // create base criteria    
    log.debug("creating GlycanSequence criteria");
    DetachedCriteria criteria;
    criteria = DetachedCriteria.forClass(GlycanSequence.class);
    // create biological contexts criteria
    DetachedCriteria bc_criteria = null;
    DetachedCriteria tax_criteria = null;
    DetachedCriteria tissue_criteria = null;
    DetachedCriteria disease_criteria = null;
    DetachedCriteria perturbation_criteria = null;
    if (taxonomyName != null || tissueName != null || diseaseName != null || perturbationName != null) {
        isNewQuery = true;
        log.debug("creating Biological context criteria");
        bc_criteria = criteria.createCriteria("glycanContexts").createCriteria("biologicalContext", "bc");
        // add taxonomy criteria        
        if (taxonomyName != null) {
            log.debug("adding taxonomy query predicates for input string '" + taxonomyName + "'");
            tax_criteria = bc_criteria.createCriteria("taxonomy", "taxa").createCriteria("taxonomySupertypes", "supertax").add(Restrictions.ilike("taxon", taxonomyName, MatchMode.EXACT));
        }
        // add tissue criteria
        if (tissueName != null) {
            log.debug("adding tissue query predicates for input string '" + tissueName + "'");
            tissue_criteria = bc_criteria.createCriteria("tissueTaxonomy", "ttax").add(Restrictions.ilike("tissueTaxon", tissueName, MatchMode.EXACT));
        }
        // add disease criteria
        if (diseaseName != null) {
            log.debug("adding disease query criteria for input string '" + diseaseName + "'");
            disease_criteria = bc_criteria.createCriteria("diseaseContexts").createCriteria("disease", "dis").add(Restrictions.ilike("diseaseName", diseaseName, MatchMode.EXACT));
        }
        if (perturbationName != null) {
            log.debug("adding perturbation query criteria for input string '" + perturbationName + "'");
            perturbation_criteria = bc_criteria.createCriteria("perturbationContexts").createCriteria("perturbation", "per").add(Restrictions.ilike("perturbationName", perturbationName, MatchMode.EXACT));
        }
    }
    // add mass criteria
    boolean mass_query_is_given = false;
    boolean params_are_ok = false;
    if (exactMass > 0 && exactMassTolerance > 0) {
        isNewQuery = true;
        mass_query_is_given = true;
        lowMass = exactMass - exactMassTolerance;
        highMass = exactMass + exactMassTolerance;
        log.debug("adding predicates for exactMass=" + exactMass + " Da +/- " + exactMassTolerance + " Da (ie: " + lowMass + "-" + highMass + " Da)");
        params_are_ok = true;
    } else if (lowMass > 0 && highMass > 0) {
        isNewQuery = true;
        mass_query_is_given = true;
        exactMass = -1;
        exactMassTolerance = -1;
        log.debug("adding predicates for mass range=(" + lowMass + ".." + highMass + " Da)");
        params_are_ok = true;
    }
    if (mass_query_is_given) {
        if (params_are_ok) {
            isNewQuery = true;
            String property = useAvgMass ? "massAverage" : "massMonoisotopic";
            criteria.add(Restrictions.between(property, new BigDecimal(lowMass), new BigDecimal(highMass)));
        } else {
            String msg = "Insufficient mass parameters given, either " + "provide an exactMass + exactMassTolerence + useAvgMass preference, " + "or provide a lowMass + highMass + useAvgMass preference";
            addActionError(msg);
            log.info(msg);
        }
    }
    Glycan glycan = null;
    if (sequenceGWS != null) {
        glycan = Glycan.fromString(sequenceGWS);
        glycan.removeReducingEndModification();
        if (glycan.isEmpty()) {
            glycan = null;
            sequenceGWS = null;
        }
    }
    if (glycan != null) {
        isNewQuery = true;
        // search structure in DB
        String glycoct = glycan.toGlycoCTCondensed();
        SugarSequence seq = new SugarSequence(glycoct);
        SubstructureQuery query = new SubstructureQuery(seq);
        if (sequencePosition != null) {
            if (sequencePosition.equals("Core") || sequencePosition.equals("Core + Terminii"))
                query.setOption(Must_Include_Reducing_Terminus);
            if (sequencePosition.equals("Terminii") || sequencePosition.equals("Core + Terminii"))
                query.setOption(Must_Include_All_Non_Reducing_Terminii);
        }
        criteria.add(query.getQueryCriterion());
    }
    if (this.additionalQueries.size() > 1) {
        isNewQuery = true;
    }
    for (SavedGlycanSequenceSearch oldQuery : this.additionalQueries) {
        DetachedCriteria oldCriteria = oldQuery.getQueryCriteria();
        criteria.add(Subqueries.propertyIn("glycanSequenceId", oldCriteria));
        oldCriteria.setProjection(Projections.distinct(Projections.property("glycanSequenceId")));
        this.currentSearch = oldQuery;
    }
    return criteria;
}
Example 42
Project: jrecruiter-master  File: UserDaoJpa.java View source code
/**
	 * Method for returning list of available job postings.
	 * @param pageSize Max number of results returned
	 * @param pageNumber Which page are you one?
	 * @param fieldSorted Which field shall be sorted
	 * @param sortOrder What is the sort order?
	 * @return List of jobs.
	 */
@SuppressWarnings("unchecked")
public List<User> getUsers(final Integer pageSize, final Integer pageNumber, Map<String, String> sortOrders, Map<String, String> userFilters) {
    List<User> users;
    if (pageSize == null) {
        throw new IllegalStateException("pageSize must not be null.");
    }
    if (pageNumber == null) {
        throw new IllegalStateException("pageNumber must not be null.");
    }
    if (sortOrders == null) {
        sortOrders = CollectionUtils.getHashMap();
    }
    if (sortOrders.isEmpty()) {
        sortOrders.put("lastName", "ASC");
    }
    if (userFilters == null) {
        userFilters = CollectionUtils.getHashMap();
    }
    Session session = (Session) entityManager.getDelegate();
    final Criteria criteria = session.createCriteria(User.class);
    for (Entry<String, String> entry : sortOrders.entrySet()) {
        if (entry.getValue().equalsIgnoreCase("DESC")) {
            criteria.addOrder(Order.desc(entry.getKey()));
        } else if (entry.getValue().equalsIgnoreCase("ASC")) {
            criteria.addOrder(Order.asc(entry.getKey()));
        } else {
            throw new IllegalStateException("SortOrder " + entry.getValue() + " is not supported.");
        }
    }
    for (Entry<String, String> entry : userFilters.entrySet()) {
        criteria.add(Restrictions.ilike(entry.getKey(), entry.getValue(), MatchMode.ANYWHERE));
    }
    criteria.setFirstResult((pageNumber - 1) * pageSize);
    criteria.setMaxResults(pageSize);
    users = criteria.list();
    return users;
}
Example 43
Project: Lemo-Data-Management-Server-master  File: ServiceCourseTitleSearch.java View source code
/**
	 * Gets the details of all courses whose title matches search text. Informations include id, title, description, 
	 * number of participants, time of first student-request, time of latest student-request.
	 * 
	 * @param text	.
	 * 
	 * @return	A List of CourseObjects containing the information.
	 */
@GET
public ResultListCourseObject getCoursesByText(@QueryParam(MetaParam.SEARCH_TEXT) final String text, @QueryParam(MetaParam.RESULT_AMOUNT) final Long count, @QueryParam(MetaParam.OFFSET) final Long offset) {
    IDBHandler dbHandler = ServerConfiguration.getInstance().getMiningDbHandler();
    List<CourseObject> result = new ArrayList<CourseObject>();
    result.add(new CourseObject());
    result.add(new CourseObject());
    if (text == null || text.equals("")) {
        return new ResultListCourseObject(result);
    }
    // Set up db-connection
    final Session session = dbHandler.getMiningSession();
    Criteria criteria = session.createCriteria(Course.class, "course");
    criteria.add(Restrictions.ilike("course.title", text, MatchMode.ANYWHERE));
    @SuppressWarnings("unchecked") final ArrayList<Course> courses = (ArrayList<Course>) criteria.list();
    criteria = session.createCriteria(Attribute.class, "attribute");
    criteria.add(Restrictions.like("attribute.name", "CourseFirstRequest"));
    Long fattId = -1l;
    if (criteria.list().size() > 0) {
        fattId = ((Attribute) criteria.list().get(criteria.list().size() - 1)).getId();
    }
    criteria = session.createCriteria(Attribute.class, "attribute");
    criteria.add(Restrictions.like("attribute.name", "CourseLastRequest"));
    Long lattId = -1l;
    if (criteria.list().size() > 0) {
        lattId = ((Attribute) criteria.list().get(criteria.list().size() - 1)).getId();
    }
    ServiceCourseDetails scd = new ServiceCourseDetails();
    for (Course courseMining : courses) {
        Long lastTime = 0L;
        Long firstTime = 0L;
        criteria = session.createCriteria(CourseAttribute.class, "courseAttribute");
        criteria.add(Restrictions.eq("courseAttribute.course.id", courseMining.getId()));
        criteria.add(Restrictions.eq("courseAttribute.attribute.id", fattId));
        if (criteria.list().size() > 0)
            firstTime = Long.valueOf(((CourseAttribute) criteria.list().get(0)).getValue());
        criteria = session.createCriteria(CourseAttribute.class, "courseAttribute");
        criteria.add(Restrictions.eq("courseAttribute.course.id", courseMining.getId()));
        criteria.add(Restrictions.eq("courseAttribute.attribute.id", lattId));
        if (criteria.list().size() > 0)
            lastTime = Long.valueOf(((CourseAttribute) criteria.list().get(0)).getValue());
        if (lastTime == 0L) {
            criteria = session.createCriteria(ILog.class, "log");
            criteria.add(Restrictions.eq("log.course.id", courseMining.getId()));
            criteria.setProjection(Projections.projectionList().add(Projections.max("log.timestamp")));
            for (int i = 0; i < criteria.list().size(); i++) {
                if (criteria.list().get(i) != null)
                    lastTime = (Long) criteria.list().get(i);
            }
        }
        if (firstTime == 0L) {
            criteria = session.createCriteria(ILog.class, "log");
            criteria.add(Restrictions.eq("log.course.id", courseMining.getId()));
            criteria.setProjection(Projections.projectionList().add(Projections.min("log.timestamp")));
            for (int i = 0; i < criteria.list().size(); i++) {
                if (criteria.list().get(i) != null)
                    firstTime = (Long) criteria.list().get(i);
            }
        }
        int scount = StudentHelper.getStudentCount(courseMining.getId());
        Long chash = scd.getCourseHash(courseMining.getId(), firstTime, lastTime);
        boolean gsupp = StudentHelper.getGenderSupport(courseMining.getId());
        final CourseObject co = new CourseObject(courseMining.getId(), courseMining.getTitle(), courseMining.getTitle(), scount, lastTime, firstTime, chash, gsupp);
        result.add(co);
    }
    session.close();
    return new ResultListCourseObject(result);
}
Example 44
Project: lemon-master  File: HibernateUtils.java View source code
/**
     * 按属性�件�数创建Criterion,辅助函数.
     * 
     * @param propertyName
     *            String
     * @param propertyValue
     *            Object
     * @param matchType
     *            MatchType
     * @return Criterion
     */
public static Criterion buildCriterion(String propertyName, Object propertyValue, MatchType matchType) {
    Assert.hasText(propertyName, "propertyName�能为空");
    Criterion criterion = null;
    // 根�MatchType构造criterion
    switch(matchType) {
        case EQ:
            criterion = Restrictions.eq(propertyName, propertyValue);
            break;
        case NOT:
            criterion = Restrictions.ne(propertyName, propertyValue);
            break;
        case LIKE:
            criterion = Restrictions.like(propertyName, (String) propertyValue, MatchMode.ANYWHERE);
            break;
        case LE:
            criterion = Restrictions.le(propertyName, propertyValue);
            break;
        case LT:
            criterion = Restrictions.lt(propertyName, propertyValue);
            break;
        case GE:
            criterion = Restrictions.ge(propertyName, propertyValue);
            break;
        case GT:
            criterion = Restrictions.gt(propertyName, propertyValue);
            break;
        case IN:
            criterion = Restrictions.in(propertyName, (Collection) propertyValue);
            break;
        case INL:
            criterion = Restrictions.isNull(propertyName);
            break;
        case NNL:
            criterion = Restrictions.isNotNull(propertyName);
            break;
        default:
            criterion = Restrictions.eq(propertyName, propertyValue);
            break;
    }
    return criterion;
}
Example 45
Project: linshare-core-master  File: GuestRepositoryImpl.java View source code
/**
	 * Search some guests. If given agument is null, it's not considered.
	 * @param mail
	 *            user mail.
	 * @param firstName
	 *            user first name.
	 * @param lastName
	 *            user last name.
	 * @param ownerLogin
	 *            login of the user who creates the searched guest(s).
	 * 
	 * @return a list of matching users.
	 */
public List<Guest> searchGuest(Account owner, String mail, String firstName, String lastName) {
    DetachedCriteria criteria = DetachedCriteria.forClass(getPersistentClass());
    criteria.add(Restrictions.eq("destroyed", 0L));
    if (mail != null) {
        criteria.add(Restrictions.ilike("mail", mail, MatchMode.ANYWHERE));
    }
    if (firstName != null) {
        criteria.add(Restrictions.ilike("firstName", firstName, MatchMode.ANYWHERE));
    }
    if (lastName != null) {
        criteria.add(Restrictions.ilike("lastName", lastName, MatchMode.ANYWHERE));
    }
    if (owner != null) {
        criteria.add(Restrictions.eq("owner", owner));
    }
    return findByCriteria(criteria);
}
Example 46
Project: openmrs-module-openhmis.commons-master  File: BaseMetadataDataServiceImpl.java View source code
@Override
@Transactional(readOnly = true)
public List<E> getByNameFragment(final String nameFragment, final boolean includeRetired, PagingInfo pagingInfo) {
    IMetadataAuthorizationPrivileges privileges = getPrivileges();
    if (privileges != null && !StringUtils.isEmpty(privileges.getGetPrivilege())) {
        PrivilegeUtil.requirePrivileges(Context.getAuthenticatedUser(), privileges.getGetPrivilege());
    }
    if (StringUtils.isEmpty(nameFragment)) {
        throw new IllegalArgumentException("The name fragment must be defined.");
    }
    if (nameFragment.length() > NAME_LENGTH) {
        throw new IllegalArgumentException("the name fragment must be less than 256 characters long.");
    }
    return executeCriteria(getEntityClass(), pagingInfo, new Action1<Criteria>() {

        @Override
        public void apply(Criteria criteria) {
            criteria.add(Restrictions.ilike("name", nameFragment, MatchMode.START));
            if (!includeRetired) {
                criteria.add(Restrictions.eq("retired", false));
            }
        }
    }, getDefaultSort());
}
Example 47
Project: openmrs_gsoc-master  File: HibernateConceptDAO.java View source code
/**
	 * @see org.openmrs.api.db.ConceptDAO#getDrugs(java.lang.String)
	 */
@SuppressWarnings("unchecked")
public List<Drug> getDrugs(String phrase) throws DAOException {
    List<String> words = ConceptWord.getUniqueWords(phrase);
    List<Drug> conceptDrugs = new Vector<Drug>();
    if (words.size() > 0) {
        Criteria searchCriteria = sessionFactory.getCurrentSession().createCriteria(Drug.class, "drug");
        searchCriteria.add(Restrictions.eq("drug.retired", false));
        Iterator<String> word = words.iterator();
        searchCriteria.add(Restrictions.like("name", word.next(), MatchMode.ANYWHERE));
        while (word.hasNext()) {
            String w = word.next();
            log.debug(w);
            searchCriteria.add(Restrictions.like("name", w, MatchMode.ANYWHERE));
        }
        searchCriteria.addOrder(Order.asc("drug.concept"));
        conceptDrugs = searchCriteria.list();
    }
    return conceptDrugs;
}
Example 48
Project: Openmrs_old-master  File: HibernateConceptDAO.java View source code
/**
	 * @see org.openmrs.api.db.ConceptDAO#getDrugs(java.lang.String)
	 */
@SuppressWarnings("unchecked")
public List<Drug> getDrugs(String phrase) throws DAOException {
    List<String> words = ConceptWord.getUniqueWords(phrase);
    List<Drug> conceptDrugs = new Vector<Drug>();
    if (words.size() > 0) {
        Criteria searchCriteria = sessionFactory.getCurrentSession().createCriteria(Drug.class, "drug");
        searchCriteria.add(Expression.eq("drug.retired", false));
        Iterator<String> word = words.iterator();
        searchCriteria.add(Expression.like("name", word.next(), MatchMode.ANYWHERE));
        while (word.hasNext()) {
            String w = word.next();
            log.debug(w);
            searchCriteria.add(Expression.like("name", w, MatchMode.ANYWHERE));
        }
        searchCriteria.addOrder(Order.asc("drug.concept"));
        conceptDrugs = searchCriteria.list();
    }
    return conceptDrugs;
}
Example 49
Project: springlab-master  File: HibernateDao.java View source code
/**
	 * 按属性�件�数创建Criterion,辅助函数.
	 */
protected Criterion buildCriterion(final String propertyName, final Object propertyValue, final MatchType matchType) {
    Assert.hasText(propertyName, "propertyName�能为空");
    Criterion criterion = null;
    //根�MatchType构造criterion
    switch(matchType) {
        case EQ:
            criterion = Restrictions.eq(propertyName, propertyValue);
            break;
        case LIKE:
            criterion = Restrictions.like(propertyName, (String) propertyValue, MatchMode.ANYWHERE);
            break;
        case LE:
            criterion = Restrictions.le(propertyName, propertyValue);
            break;
        case LT:
            criterion = Restrictions.lt(propertyName, propertyValue);
            break;
        case GE:
            criterion = Restrictions.ge(propertyName, propertyValue);
            break;
        case GT:
            criterion = Restrictions.gt(propertyName, propertyValue);
    }
    return criterion;
}
Example 50
Project: springside-core-3.3.4.x-master  File: HibernateDao.java View source code
/**
	 * 按属性�件�数创建Criterion,辅助函数.
	 */
protected Criterion buildCriterion(final String propertyName, final Object propertyValue, final MatchType matchType) {
    Assert.hasText(propertyName, "propertyName�能为空");
    Criterion criterion = null;
    SimpleExpression se = null;
    //根�MatchType构造criterion
    switch(matchType) {
        case EQ:
            se = Restrictions.eq(propertyName, propertyValue);
            criterion = ignoreCase(se, propertyName, propertyValue);
            break;
        case NE:
            criterion = Restrictions.ne(propertyName, propertyValue);
            break;
        case LIKE:
            if (propertyValue instanceof String) {
                se = Restrictions.like(propertyName, (String) propertyValue, MatchMode.ANYWHERE);
                criterion = ignoreCase(se, propertyName, propertyValue);
            } else {
                logger.warn("属性{}使用LIKE查询,为�字符型,实际类型为:{},自动使用EQ查询", propertyName, propertyValue.getClass().getName());
                se = Restrictions.eq(propertyName, propertyValue);
                criterion = ignoreCase(se, propertyName, propertyValue);
            }
            break;
        case RLIKE:
            if (propertyValue instanceof String) {
                se = Restrictions.like(propertyName, (String) propertyValue, MatchMode.START);
                criterion = ignoreCase(se, propertyName, propertyValue);
            } else {
                logger.warn("属性{}使用LLIKE查询,为�字符型,实际类型为:{},自动使用EQ查询", propertyName, propertyValue.getClass().getName());
                se = Restrictions.eq(propertyName, propertyValue);
                criterion = ignoreCase(se, propertyName, propertyValue);
            }
            break;
        case LLIKE:
            if (propertyValue instanceof String) {
                se = Restrictions.like(propertyName, (String) propertyValue, MatchMode.END);
                criterion = ignoreCase(se, propertyName, propertyValue);
            } else {
                logger.warn("属性{}使用RLIKE查询,为�字符型,实际类型为:{},自动使用EQ查询", propertyName, propertyValue.getClass().getName());
                se = Restrictions.eq(propertyName, propertyValue);
                criterion = ignoreCase(se, propertyName, propertyValue);
            }
            break;
        case LE:
            criterion = Restrictions.le(propertyName, propertyValue);
            break;
        case LT:
            criterion = Restrictions.lt(propertyName, propertyValue);
            break;
        case GE:
            criterion = Restrictions.ge(propertyName, propertyValue);
            break;
        case GT:
            criterion = Restrictions.gt(propertyName, propertyValue);
            break;
        case NN:
            criterion = Restrictions.isNotNull(propertyName);
            break;
        case IN:
            criterion = Restrictions.in(propertyName, (Object[]) propertyValue);
            break;
        case BTD:
            Date dateValue = (Date) propertyValue;
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(dateValue);
            calendar.add(Calendar.DAY_OF_MONTH, 1);
            criterion = Restrictions.and(Restrictions.ge(propertyName, propertyValue), Restrictions.le(propertyName, calendar.getTime()));
            break;
    }
    return criterion;
}
Example 51
Project: voms-admin-server-master  File: AuditSearchDAOHibernate.java View source code
protected Criteria buildCriteriaFromParams(AuditLogSearchParams sp) {
    Criteria crit = createCriteria();
    crit.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
    if (sp.getFromTime() != null) {
        crit.add(Restrictions.ge("timestamp", sp.getFromTime()));
    }
    if (sp.getToTime() != null) {
        crit.add(Restrictions.le("timestamp", sp.getToTime()));
    }
    if (sp.getFilterString() != null && !sp.getFilterString().trim().equals("")) {
        if (sp.getFilterType().equals(AuditLogSearchParams.FULL_SEARCH_KEY)) {
            // Full search is basically search over principal
            // and audit event data point values
            String filterString = String.format("%%%s%%", sp.getFilterString());
            // This is due to another ugly limitation of Hibernate 3.3
            // which does not support criteria queries on embedded
            // collections
            // See https://hibernate.atlassian.net/browse/HHH-869
            crit.add(Restrictions.disjunction().add(Restrictions.sqlRestriction("{alias}.event_id in (select ae.event_id from audit_event ae, audit_event_data aed where ae.event_id = aed.event_id and aed.value like ?)", filterString, StringType.INSTANCE)).add(Restrictions.like("principal", sp.getFilterString().trim(), MatchMode.ANYWHERE)));
        } else {
            crit.add(Restrictions.like(sp.getFilterType(), sp.getFilterString().trim(), MatchMode.ANYWHERE));
        }
    }
    if (sp.getFirstResult() != null) {
        crit.setFirstResult(sp.getFirstResult());
    }
    if (sp.getMaxResults() != null) {
        crit.setMaxResults(sp.getMaxResults());
    }
    crit.addOrder(Order.desc("timestamp"));
    return crit;
}
Example 52
Project: webpasswordsafe-master  File: PasswordDAOHibernate.java View source code
@Override
@SuppressWarnings("unchecked")
public List<Password> findPasswordByFuzzySearch(String query, User user, boolean activeOnly, Collection<Tag> tags, Match tagMatch) {
    //kludge to not use ilike on text column if MSSQL
    boolean isMSSQL = ((SessionFactoryImpl) getSessionFactory()).getDialect().toString().contains("SQLServer");
    Criteria crit = getSession().createCriteria(getPersistentClass());
    crit.setFetchMode("tags", FetchMode.JOIN);
    crit.add(Restrictions.or(Restrictions.or(Restrictions.ilike("name", query, MatchMode.ANYWHERE), Restrictions.ilike("username", query, MatchMode.ANYWHERE)), isMSSQL ? Restrictions.like("notes", query, MatchMode.ANYWHERE) : Restrictions.ilike("notes", query, MatchMode.ANYWHERE)));
    if (activeOnly) {
        crit.add(Restrictions.eq("active", true));
    }
    Criterion tagsCriterion = null;
    for (Tag tag : tags) {
        Criterion tc = Restrictions.sqlRestriction("? in (select tag_id from password_tags where password_id = {alias}.id)", tag.getId(), StandardBasicTypes.LONG);
        if (null == tagsCriterion) {
            tagsCriterion = tc;
        } else {
            tagsCriterion = tagMatch.equals(Match.AND) ? Restrictions.and(tagsCriterion, tc) : Restrictions.or(tagsCriterion, tc);
        }
    }
    if (tagsCriterion != null)
        crit.add(tagsCriterion);
    crit.createAlias("permissions", "pm");
    crit.add(Restrictions.in("pm.accessLevel", new String[] { AccessLevel.READ.name(), AccessLevel.WRITE.name(), AccessLevel.GRANT.name() }));
    if (!authorizer.isAuthorized(user, Function.BYPASS_PASSWORD_PERMISSIONS.name())) {
        DetachedCriteria groupQuery = DetachedCriteria.forClass(Group.class);
        groupQuery.setProjection(Projections.id());
        groupQuery.createCriteria("users", "u").add(Restrictions.eq("u.id", user.getId()));
        crit.add(Restrictions.or(Restrictions.eq("pm.subject", user), Subqueries.propertyIn("pm.subject", groupQuery)));
    }
    crit.addOrder(Order.asc("name"));
    crit.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
    return crit.list();
}
Example 53
Project: abiquo-master  File: VirtualDatacenterDAO.java View source code
public Collection<VirtualDatacenter> findByEnterpriseAndDatacenterFilter(final Enterprise enterprise, final Datacenter datacenter, final User user, final FilterOptions filterOptions) {
    Collection<Criterion> restrictions = new ArrayList<Criterion>();
    if (enterprise != null) {
        restrictions.add(sameEnterprise(enterprise));
    }
    if (datacenter != null) {
        restrictions.add(sameDatacenter(datacenter));
    }
    if (user != null) {
        restrictions.add(availableToUser(user));
    }
    if (filterOptions != null) {
        restrictions.add(Restrictions.like(VirtualDatacenter.NAME_PROPERTY, filterOptions.getFilter(), MatchMode.ANYWHERE));
    }
    return findVirtualDatacentersByCriterions(restrictions, filterOptions);
}
Example 54
Project: BACKUP_FROM_SVN-master  File: Main.java View source code
/**
	 * Demonstrates query by example
	 */
public void viewAuctionsByDescription(String description, int condition) throws Exception {
    String msg = "Viewing auctions containing: " + description;
    if (condition > 0)
        msg += " with condition: " + condition + "/10";
    AuctionItem item = new AuctionItem();
    item.setDescription(description);
    item.setCondition(condition);
    Session s = factory.openSession();
    Transaction tx = null;
    try {
        tx = s.beginTransaction();
        Iterator iter = s.createCriteria(AuctionItem.class).add(Example.create(item).enableLike(MatchMode.ANYWHERE).ignoreCase().excludeZeroes()).list().iterator();
        System.out.println(msg);
        while (iter.hasNext()) {
            item = (AuctionItem) iter.next();
            System.out.println("Item: " + item.getId() + " - " + item.getDescription());
        }
        System.out.println();
        tx.commit();
    } catch (Exception e) {
        if (tx != null)
            tx.rollback();
        throw e;
    } finally {
        s.close();
    }
}
Example 55
Project: dddlib-master  File: EntityRepositoryHibernate.java View source code
/*
     * (non-Javadoc)
     * @see org.dayatang.domain.EntityRepository#findByExample(org.dayatang.domain.Entity, org.dayatang.domain.ExampleSettings)
     */
@Override
public <T extends Entity, E extends T> List<T> findByExample(final E example, final ExampleSettings<T> settings) {
    Example theExample = Example.create(example);
    if (settings.isLikeEnabled()) {
        theExample.enableLike(MatchMode.ANYWHERE);
    }
    if (settings.isIgnoreCaseEnabled()) {
        theExample.ignoreCase();
    }
    if (settings.isExcludeNone()) {
        theExample.excludeNone();
    }
    if (settings.isExcludeZeroes()) {
        theExample.excludeZeroes();
    }
    for (String propName : settings.getExcludedProperties()) {
        theExample.excludeProperty(propName);
    }
    return getSession().createCriteria(settings.getEntityClass()).add(theExample).list();
}
Example 56
Project: eucalyptus-fork-2.0-master  File: DatabaseAuthProvider.java View source code
@Override
public User lookupCertificate(X509Certificate cert) throws NoSuchUserException {
    String certPem = B64.url.encString(PEMFiles.getBytes(cert));
    UserEntity searchUser = new UserEntity();
    searchUser.setEnabled(true);
    X509Cert searchCert = new X509Cert();
    searchCert.setPemCertificate(certPem);
    searchCert.setRevoked(null);
    EntityWrapper<UserEntity> db = EntityWrapper.get(searchUser);
    Session session = db.getSession();
    try {
        Example qbeUser = Example.create(searchUser).enableLike(MatchMode.EXACT);
        Example qbeCert = Example.create(searchCert).enableLike(MatchMode.EXACT);
        List<UserEntity> users = (List<UserEntity>) session.createCriteria(UserEntity.class).setCacheable(true).add(qbeUser).createCriteria("certificates").setCacheable(true).add(qbeCert).list();
        UserEntity ret = users.size() == 1 ? users.get(0) : null;
        int size = users.size();
        if (ret != null) {
            return new DatabaseWrappedUser(ret);
        } else {
            throw new GeneralSecurityException((size == 0) ? "No user with the specified certificate." : "Multiple users with the same certificate.");
        }
    } catch (Throwable t) {
        throw new NoSuchUserException(t);
    } finally {
        db.rollback();
    }
}
Example 57
Project: hospitalcore-master  File: HibernatePatientDashboardDAO.java View source code
@SuppressWarnings("unchecked")
public List<Concept> searchConceptsByNameAndClass(String text, ConceptClass clazz) throws DAOException {
    Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Concept.class);
    criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
    criteria.add(Expression.eq("retired", false));
    criteria.add(Restrictions.eq("conceptClass", clazz));
    if (StringUtils.isNotBlank(text)) {
        criteria.createAlias("names", "names");
        criteria.add(Expression.like("names.name", text, MatchMode.ANYWHERE));
    }
    return criteria.list();
}
Example 58
Project: jshoperx-master  File: GoodsTAction.java View source code
/**
	 * æ ¹æ?®å•†å“?å??称查询商å“?
	 */
private void findGoodsByGoodsname() {
    int currentPage = page;
    int lineSize = rp;
    Criterion criterion = Restrictions.like(this.getQtype(), this.getQuery().trim(), MatchMode.ANYWHERE);
    total = this.goodsTService.count(GoodsT.class, criterion).intValue();
    if (StringUtils.isNotBlank(this.getSortname()) && StringUtils.isNotBlank(this.getSortorder())) {
        Order order = null;
        if (StringUtils.equals(this.getSortorder(), StaticKey.ASC)) {
            order = Order.asc(this.getSortname());
        } else {
            order = Order.desc(this.getSortname());
        }
        List<GoodsT> list = this.goodsTService.findByCriteriaByPage(GoodsT.class, criterion, order, currentPage, lineSize);
        this.processGoodsList(list);
    }
}
Example 59
Project: openmrs-master  File: HibernateConceptDAO.java View source code
/**
	 * @see org.openmrs.api.db.ConceptDAO#getDrugs(java.lang.String)
	 */
@SuppressWarnings("unchecked")
public List<Drug> getDrugs(String phrase) throws DAOException {
    List<String> words = ConceptWord.getUniqueWords(phrase);
    List<Drug> conceptDrugs = new Vector<Drug>();
    if (words.size() > 0) {
        Criteria searchCriteria = sessionFactory.getCurrentSession().createCriteria(Drug.class, "drug");
        searchCriteria.add(Expression.eq("drug.retired", false));
        Iterator<String> word = words.iterator();
        searchCriteria.add(Expression.like("name", word.next(), MatchMode.ANYWHERE));
        while (word.hasNext()) {
            String w = word.next();
            log.debug(w);
            searchCriteria.add(Expression.like("name", w, MatchMode.ANYWHERE));
        }
        searchCriteria.addOrder(Order.asc("drug.concept"));
        conceptDrugs = searchCriteria.list();
    }
    return conceptDrugs;
}
Example 60
Project: openmrs-maven-master  File: HibernateConceptDAO.java View source code
/**
	 * @see org.openmrs.api.db.ConceptDAO#getDrugs(java.lang.String)
	 */
@SuppressWarnings("unchecked")
public List<Drug> getDrugs(String phrase) throws DAOException {
    List<String> words = ConceptWord.getUniqueWords(phrase);
    List<Drug> conceptDrugs = new Vector<Drug>();
    if (words.size() > 0) {
        Criteria searchCriteria = sessionFactory.getCurrentSession().createCriteria(Drug.class, "drug");
        searchCriteria.add(Expression.eq("drug.retired", false));
        Iterator<String> word = words.iterator();
        searchCriteria.add(Expression.like("name", word.next(), MatchMode.ANYWHERE));
        while (word.hasNext()) {
            String w = word.next();
            log.debug(w);
            searchCriteria.add(Expression.like("name", w, MatchMode.ANYWHERE));
        }
        searchCriteria.addOrder(Order.asc("drug.concept"));
        conceptDrugs = searchCriteria.list();
    }
    return conceptDrugs;
}
Example 61
Project: qalingo-engine-master  File: ProductDao.java View source code
public List<ProductMarketing> findProductMarketings(final String text, Object... params) {
    Criteria criteria = createDefaultCriteria(ProductMarketing.class);
    handleSpecificProductMarketingFetchMode(criteria, params);
    criteria.add(Restrictions.or(Restrictions.like("code", text, MatchMode.ANYWHERE), Restrictions.like("name", text, MatchMode.ANYWHERE), Restrictions.like("description", text, MatchMode.ANYWHERE)));
    criteria.addOrder(Order.asc("id"));
    @SuppressWarnings("unchecked") List<ProductMarketing> productMarketings = criteria.list();
    return productMarketings;
}
Example 62
Project: beanfuse-master  File: CriterionUtils.java View source code
public static Example getExampleCriterion(Object entity, String[] excludePropertes, MatchMode mode) {
    Example example = Example.create(entity).setPropertySelector(new NotEmptyPropertySelector());
    if (null != mode) {
        example.enableLike(mode);
    }
    if (null != excludePropertes) {
        for (int i = 0; i < excludePropertes.length; i++) {
            example.excludeProperty(excludePropertes[i]);
        }
    }
    return example;
}
Example 63
Project: eucalyptus-master  File: WalrusFSManager.java View source code
@Override
public ListBucketResponseType listBucket(ListBucketType request) throws WalrusException {
    ListBucketResponseType reply = (ListBucketResponseType) request.getReply();
    Context ctx = Contexts.lookup();
    String bucketName = request.getBucket();
    // Lookup bucket
    try {
        Transactions.find(new BucketInfo(bucketName));
    } catch (NoSuchElementException e) {
        throw new NoSuchBucketException(bucketName);
    } catch (Exception e) {
        LOG.error("Failed to look up metadata for bucket=" + bucketName, e);
        throw new InternalErrorException("Failed to lookup bucket " + bucketName, e);
    }
    String prefix = request.getPrefix();
    String delimiter = request.getDelimiter();
    String marker = request.getMarker();
    int maxKeys = -1;
    reply.setName(bucketName);
    reply.setIsTruncated(false);
    reply.setPrefix(prefix);
    reply.setMarker(marker);
    reply.setDelimiter(delimiter);
    if (request.getMaxKeys() != null) {
        maxKeys = Integer.parseInt(request.getMaxKeys());
        if (maxKeys < 0) {
            throw new InvalidArgumentException("max-keys", "Argument max-keys must be an integer between 0 and " + Integer.MAX_VALUE);
        } else if (maxKeys == 0) {
            // No keys requested, so just return
            reply.setMaxKeys(maxKeys);
            reply.setContents(new ArrayList<ListEntry>());
            reply.setCommonPrefixesList(new ArrayList<CommonPrefixesEntry>());
            return reply;
        }
    } else {
        maxKeys = WalrusProperties.MAX_KEYS;
        reply.setMaxKeys(maxKeys);
    }
    try (TransactionResource tr = Entities.transactionFor(ObjectInfo.class)) {
        final int queryStrideSize = maxKeys + 1;
        ObjectInfo searchObj = new ObjectInfo();
        searchObj.setBucketName(bucketName);
        Criteria objCriteria = Entities.createCriteria(ObjectInfo.class);
        objCriteria.add(Example.create(searchObj));
        objCriteria.addOrder(Order.asc("objectKey"));
        // add one to, hopefully, indicate truncation in one call
        objCriteria.setMaxResults(queryStrideSize);
        objCriteria.setReadOnly(true);
        if (!Strings.isNullOrEmpty(marker)) {
            // The result set should be exclusive of the marker. marker could be a common prefix from a previous response. Look for keys that
            // lexicographically follow the marker and don't contain the marker as the prefix.
            objCriteria.add(Restrictions.gt("objectKey", marker));
        } else {
            marker = "";
        }
        if (!Strings.isNullOrEmpty(prefix)) {
            objCriteria.add(Restrictions.like("objectKey", prefix, MatchMode.START));
        } else {
            prefix = "";
        }
        // Ensure not null.
        if (Strings.isNullOrEmpty(delimiter)) {
            delimiter = "";
        }
        List<ObjectInfo> objectInfos = null;
        int resultKeyCount = 0;
        // contents for reply
        ArrayList<ListEntry> contents = new ArrayList<ListEntry>();
        String nextMarker = null;
        TreeSet<String> commonPrefixes = new TreeSet<String>();
        int firstResult = -1;
        // same owner for every object
        CanonicalUser owner = buildCanonicalUser(ctx.getUser());
        // Iterate over result sets of size maxkeys + 1
        do {
            // Start listing from the 0th element and increment the first element to be listed by the query size
            objCriteria.setFirstResult(queryStrideSize * (++firstResult));
            objectInfos = (List<ObjectInfo>) objCriteria.list();
            if (objectInfos.size() > 0) {
                for (ObjectInfo objectInfo : objectInfos) {
                    String objectKey = objectInfo.getObjectKey();
                    // Check if it will get aggregated as a commonprefix
                    if (!Strings.isNullOrEmpty(delimiter)) {
                        // Split the substring to a maximum of two parts as we need a result containing trailing strings. For instance
                        // if "x" is delimiter and key string is also "x", then this key should be included in common prefixes.
                        // "x".split("x") gives 0 strings which causes the subsequent logic to skip the key where as
                        // "x".split("x", 2) gives 2 empty strings which is what the logic expects
                        String[] parts = objectKey.substring(prefix.length()).split(delimiter, 2);
                        if (parts.length > 1) {
                            String prefixString = prefix + parts[0] + delimiter;
                            if (!StringUtils.equals(prefixString, marker) && !commonPrefixes.contains(prefixString)) {
                                if (resultKeyCount == maxKeys) {
                                    // This is a new record, so we know we're truncating if this is true
                                    reply.setNextMarker(nextMarker);
                                    reply.setIsTruncated(true);
                                    resultKeyCount++;
                                    break;
                                }
                                commonPrefixes.add(prefixString);
                                // count the unique commonprefix as a single return entry
                                resultKeyCount++;
                                // If the common prefixes hit the limit set by max-keys, next-marker is the last common prefix
                                if (resultKeyCount == maxKeys) {
                                    nextMarker = prefixString;
                                }
                            }
                            continue;
                        }
                    }
                    if (resultKeyCount == maxKeys) {
                        // This is a new (non-commonprefix) record, so we know we're truncating
                        reply.setNextMarker(nextMarker);
                        reply.setIsTruncated(true);
                        resultKeyCount++;
                        break;
                    }
                    // Process the entry as a full key listing
                    ListEntry listEntry = new ListEntry();
                    listEntry.setKey(objectKey);
                    listEntry.setEtag(objectInfo.getEtag());
                    listEntry.setLastModified(DateFormatter.dateToListingFormattedString(objectInfo.getLastModified()));
                    listEntry.setStorageClass(objectInfo.getStorageClass());
                    listEntry.setSize(objectInfo.getSize());
                    listEntry.setStorageClass(objectInfo.getStorageClass());
                    listEntry.setOwner(owner);
                    contents.add(listEntry);
                    resultKeyCount++;
                    // If max keys have been collected, set the next-marker. It might be needed for the response if the list is truncated
                    if (resultKeyCount == maxKeys) {
                        nextMarker = objectKey;
                    }
                }
            }
            if (resultKeyCount <= maxKeys && objectInfos.size() <= maxKeys) {
                break;
            }
        } while (resultKeyCount <= maxKeys);
        tr.commit();
        reply.setContents(contents);
        // Prefixes are already sorted, add them to the proper data structures and populate the reply
        if (!commonPrefixes.isEmpty()) {
            ArrayList<CommonPrefixesEntry> commonPrefixesList = new ArrayList<CommonPrefixesEntry>();
            for (String prefixEntry : commonPrefixes) {
                commonPrefixesList.add(new CommonPrefixesEntry(prefixEntry));
            }
            reply.setCommonPrefixesList(commonPrefixesList);
        }
        return reply;
    } catch (Exception e) {
        LOG.error("Failed to lookup metadata for objects in bucket=" + bucketName, e);
        throw new InternalErrorException("Failed to lookup metadata for objects in bucket=" + bucketName, e);
    }
}
Example 64
Project: openmicroscopy-master  File: QueryImpl.java View source code
@Override
@RolesAllowed("user")
@SuppressWarnings("unchecked")
public <T extends IObject> List<T> findAllByString(final Class<T> klass, final String fieldName, final String value, final boolean caseSensitive, final Filter filter) throws ApiUsageException {
    return (List<T>) getHibernateTemplate().execute(new HibernateCallback() {

        public Object doInHibernate(Session session) throws HibernateException {
            Criteria c = session.createCriteria(klass);
            parseFilter(c, filter);
            if (caseSensitive) {
                c.add(Restrictions.like(fieldName, value, MatchMode.ANYWHERE));
            } else {
                c.add(Restrictions.ilike(fieldName, value, MatchMode.ANYWHERE));
            }
            return c.list();
        }
    });
}
Example 65
Project: ProjectModel-master  File: LookupRepositoryImpl.java View source code
private Criteria createStandardFieldFilterCriteria(Session session, String domainClassName, IStandardFieldLookupProfile example, Boolean activeSetting) {
    final Example ex = Example.create(example);
    ex.enableLike(MatchMode.START);
    ex.ignoreCase();
    ex.excludeProperty("active");
    Criteria crit = session.createCriteria(domainClassName);
    crit.add(ex);
    // example, so we have to do it ourselves.  argh...
    if (!Utils.isBlankOrNull(example.getCode())) {
        crit.add(Restrictions.ilike("code", example.getCode().toLowerCase() + "%"));
    }
    if (activeSetting != null) {
        crit.add(Restrictions.eq("active", activeSetting));
    }
    return crit;
}
Example 66
Project: smart-dao-master  File: AbstractDAO.java View source code
private Criterion getCriterion(String element, QueryParameter queryParamemter) {
    OperatorType operator = getOperator(queryParamemter);
    Object parameter = getValue(queryParamemter);
    switch(operator) {
        case OPERATOR_EQUAL:
            {
                return Expression.eq(element, parameter);
            }
        case OPERATOR_LESSER:
            {
                return Expression.lt(element, parameter);
            }
        case OPERATOR_LESSER_EQUAL:
            {
                return Expression.le(element, parameter);
            }
        case OPERATOR_GREATER:
            {
                return Expression.gt(element, parameter);
            }
        case OPERATOR_GREATER_EQUAL:
            {
                return Expression.ge(element, parameter);
            }
        case OPERATOR_NOT_EQUAL:
            {
                return Expression.ne(element, parameter);
            }
        case OPERATOR_IS_NULL:
            {
                return Expression.isNull(element);
            }
        case OPERATOR_IS_NOT_NULL:
            {
                return Expression.isNotNull(element);
            }
        case OPERATOR_IS_EMPTY:
            {
                return Expression.isEmpty(element);
            }
        case OPERATOR_IS_NOT_EMPTY:
            {
                return Expression.isNotEmpty(element);
            }
        case OPERATOR_STRING_LIKE:
            {
                MatchMode hibernateMatchMode;
                com.smartitengineering.dao.common.queryparam.MatchMode matchMode = getMatchMode(queryParamemter);
                if (matchMode == null) {
                    matchMode = com.smartitengineering.dao.common.queryparam.MatchMode.EXACT;
                }
                switch(matchMode) {
                    case END:
                        hibernateMatchMode = MatchMode.END;
                        break;
                    case EXACT:
                        hibernateMatchMode = MatchMode.EXACT;
                        break;
                    case START:
                        hibernateMatchMode = MatchMode.START;
                        break;
                    default:
                    case ANYWHERE:
                        hibernateMatchMode = MatchMode.ANYWHERE;
                        break;
                }
                return Expression.like(element, parameter.toString(), hibernateMatchMode);
            }
        case OPERATOR_BETWEEN:
            {
                parameter = getFirstParameter(queryParamemter);
                Object parameter2 = getSecondParameter(queryParamemter);
                return Expression.between(element, parameter, parameter2);
            }
        case OPERATOR_IS_IN:
            {
                Collection inCollectin = QueryParameterCastHelper.MULTI_OPERAND_PARAM_HELPER.cast(queryParamemter).getValues();
                return Restrictions.in(element, inCollectin);
            }
        case OPERATOR_IS_NOT_IN:
            {
                Collection inCollectin = QueryParameterCastHelper.MULTI_OPERAND_PARAM_HELPER.cast(queryParamemter).getValues();
                return Restrictions.not(Restrictions.in(element, inCollectin));
            }
    }
    return null;
}
Example 67
Project: SOS-master  File: HibernateGetObservationHelper.java View source code
/**
     * Get the Hibernate Criterion for the requested result filter
     *
     * @param resultFilter
     *            Requested result filter
     * @return Hibernate Criterion
     * @throws CodedException
     *             If the requested result filter is not supported
     */
public static Criterion getCriterionForComparisonFilter(ComparisonFilter resultFilter) throws CodedException {
    if (ComparisonOperator.PropertyIsLike.equals(resultFilter.getOperator())) {
        checkValueReferenceForResultFilter(resultFilter.getValueReference());
        if (resultFilter.isSetEscapeString()) {
            return HibernateCriterionHelper.getLikeExpression(Observation.DESCRIPTION, checkValueForWildcardSingleCharAndEscape(resultFilter), MatchMode.ANYWHERE, Constants.DOLLAR_CHAR, true);
        } else {
            return Restrictions.like(Observation.DESCRIPTION, checkValueForWildcardSingleCharAndEscape(resultFilter), MatchMode.ANYWHERE);
        }
    } else {
        throw new NoApplicableCodeException().withMessage("The requested comparison filter {} is not supported! Only {} is supported!", resultFilter.getOperator().name(), ComparisonOperator.PropertyIsLike.name());
    }
}
Example 68
Project: tapestry-model-master  File: HibernatePersistenceServiceImpl.java View source code
public List getInstances(final Object example, final TynamoClassDescriptor classDescriptor) {
    //create Criteria instance
    DetachedCriteria searchCriteria = DetachedCriteria.forClass(example.getClass());
    searchCriteria = alterCriteria(example.getClass(), searchCriteria);
    //loop over the example object's PropertyDescriptors
    for (TynamoPropertyDescriptor propertyDescriptor : classDescriptor.getPropertyDescriptors()) {
        //only add a Criterion to the Criteria instance if this property is searchable
        if (propertyDescriptor.isSearchable()) {
            String propertyName = propertyDescriptor.getName();
            Class propertyClass = propertyDescriptor.getPropertyType();
            Object value = getPropertyAccess().get(example, propertyName);
            //only add a Criterion to the Criteria instance if the value for this property is non-null
            if (value != null) {
                if (String.class.isAssignableFrom(propertyClass) && ((String) value).length() > 0) {
                    searchCriteria.add(Restrictions.like(propertyName, value.toString(), MatchMode.ANYWHERE));
                } else /**
					 * 'one'-end of many-to-one, one-to-one
					 *
					 * Just match the identifier
					 */
                if (propertyDescriptor.isObjectReference()) {
                    Serializable identifierValue = getIdentifier(value, descriptorService.getClassDescriptor(propertyDescriptor.getBeanType()));
                    searchCriteria.createCriteria(propertyName).add(Restrictions.idEq(identifierValue));
                } else if (propertyClass.isPrimitive()) {
                    //primitive types: ignore zeroes in case of numeric types, ignore booleans anyway (TODO come up with something...)
                    if (!propertyClass.equals(boolean.class) && ((Number) value).longValue() != 0) {
                        searchCriteria.add(Restrictions.eq(propertyName, value));
                    }
                } else if (propertyDescriptor.isCollection()) {
                    //one-to-many or many-to-many
                    CollectionDescriptor collectionDescriptor = (CollectionDescriptor) propertyDescriptor;
                    TynamoClassDescriptor collectionClassDescriptor = descriptorService.getClassDescriptor(collectionDescriptor.getElementType());
                    if (collectionClassDescriptor != null) {
                        String identifierName = collectionClassDescriptor.getIdentifierDescriptor().getName();
                        Collection<Serializable> identifierValues = new ArrayList<Serializable>();
                        Collection associatedItems = (Collection) value;
                        if (associatedItems != null && associatedItems.size() > 0) {
                            for (Object o : associatedItems) {
                                identifierValues.add(getIdentifier(o, collectionClassDescriptor));
                            }
                            //add a 'value IN collection' restriction
                            searchCriteria.createCriteria(propertyName).add(Restrictions.in(identifierName, identifierValues));
                        }
                    }
                }
            }
        }
    }
    searchCriteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
    // and obtain the Session from it
    return searchCriteria.getExecutableCriteria(getSession()).list();
}
Example 69
Project: dkpro-uby-master  File: UbyStatistics.java View source code
/**
	 * Counts the number of {@link SenseAxis} instances between two {@link Lexicon} instances
	 * identified by their name. The counted sense axes are filtered by the
	 * specified type.<p>
	 * <b>Important properties of this method:</b>
	 * <ul>
	 * 		<li>Only alignments between {@link Sense} instances are considered.</li>
	 * 		<li>The sources of the alignments are not distinguished.</li>
	 * 		<li>The lexicons are identified by identifier prefixes of the aligned senses.</li>
	 * </ul>
	 * 		
	 * @param type
	 * 			Type of sense axes to be considered when counting
	 * 
	 * @param lex1Name
	 * 			The name of the first of two lexicons between which sense axes should be counted
	 * 
	 * @param lex2Name
	 * 			The name of the second of two lexicons between which sense axes should be counted
	 * 
	 * @return the number of sense axes between the lexicons filtered by the specified sense axes type.
	 * This method returns zero if a lexicon with the specified name does not exist or one of the
	 * consumed arguments is null.
	 * 
	 * @see ESenseAxisType
	 */
public long countSenseAxesPerLexiconPair(ESenseAxisType type, String lex1Name, String lex2Name) {
    // get prefix for res1Name
    Criteria c1 = session.createCriteria(Sense.class, "s");
    c1 = c1.createCriteria("lexicalEntry");
    c1 = c1.createCriteria("lexicon");
    c1 = c1.add(Restrictions.eq("name", lex1Name));
    c1 = c1.setProjection(Projections.property("s.id"));
    c1 = c1.setMaxResults(1);
    String res1 = (String) c1.uniqueResult();
    //get prefix for res2Name
    Criteria c2 = session.createCriteria(Sense.class, "s");
    c2 = c2.createCriteria("lexicalEntry");
    c2 = c2.createCriteria("lexicon");
    c2 = c2.add(Restrictions.eq("name", lex2Name));
    c2 = c2.setProjection(Projections.property("s.id"));
    c2 = c2.setMaxResults(1);
    String res2 = (String) c2.uniqueResult();
    String pref1 = "";
    String pref2 = "";
    if (res1 != null && res2 != null) {
        pref1 = res1.split("_")[0];
        if (res1.split("_")[1].equals("en") || res1.split("_")[1].equals("de")) {
            pref1 += "_" + res1.split("_")[1];
        }
        pref2 = res2.split("_")[0];
        if (res2.split("_")[1].equals("en") || res2.split("_")[1].equals("de")) {
            pref2 += "_" + res2.split("_")[1];
        }
        // get alignments with these prefixes
        Criteria criteria = session.createCriteria(SenseAxis.class);
        criteria = criteria.add(Restrictions.eq("senseAxisType", type));
        criteria = criteria.add(Restrictions.like("senseOne.id", pref1, MatchMode.START));
        criteria = criteria.add(Restrictions.like("senseTwo.id", pref2, MatchMode.START));
        criteria = criteria.setProjection(Projections.rowCount());
        return (Long) criteria.uniqueResult();
    } else {
        return 0L;
    }
}
Example 70
Project: enterprise-app-master  File: DefaultHbnContainer.java View source code
/**
	 * Returns a Restriction accordingly to the given Filter.
	 * @param Filter to construct the Restriction object.
	 * @param clazz property class.
	 * @return a Restriction object for the given Filter.
	 */
public Criterion getCustomRestriction(StringContainerFilter filter, Class<?> clazz) {
    Criterion criterion = null;
    if (clazz.equals(String.class)) {
        if (filter.ignoreCase) {
            criterion = Restrictions.ilike(filter.getPropertyId().toString(), filter.filterString, filter.onlyMatchPrefix ? MatchMode.START : MatchMode.ANYWHERE);
        } else {
            criterion = Restrictions.like(filter.getPropertyId().toString(), filter.filterString, filter.onlyMatchPrefix ? MatchMode.START : MatchMode.ANYWHERE);
        }
    } else if (clazz.equals(Integer.class)) {
        try {
            criterion = Restrictions.eq(filter.getPropertyId().toString(), new Integer(filter.filterString));
        } catch (NumberFormatException e) {
        }
    } else if (clazz.equals(Long.class)) {
        try {
            criterion = Restrictions.eq(filter.getPropertyId().toString(), new Long(filter.filterString));
        } catch (NumberFormatException e) {
        }
    } else if (clazz.equals(Double.class)) {
        try {
            criterion = Restrictions.eq(filter.getPropertyId().toString(), new Double(filter.filterString));
        } catch (NumberFormatException e) {
        }
    } else if (clazz.equals(Float.class)) {
        try {
            criterion = Restrictions.eq(filter.getPropertyId().toString(), new Double(filter.filterString));
        } catch (NumberFormatException e) {
        }
    } else if (clazz.equals(BigDecimal.class)) {
        try {
            criterion = Restrictions.eq(filter.getPropertyId().toString(), new BigDecimal(filter.filterString));
        } catch (NumberFormatException e) {
        }
    } else if (clazz.equals(Date.class)) {
        try {
            Date date1;
            Date date2;
            if (filter.filterString.isEmpty()) {
                date1 = new Date(Long.MIN_VALUE);
            } else {
                int length = filter.filterString.length() < Utils.getDateTimeFormatPattern().length() ? filter.filterString.length() : Utils.getDateTimeFormatPattern().length();
                date1 = new SimpleDateFormat(Utils.getDateTimeFormatPattern().substring(0, length)).parse(filter.filterString);
            }
            if (filter.filterString2.isEmpty()) {
                date2 = Utils.getMaxDate();
            } else {
                int length = filter.filterString2.length() < Utils.getDateTimeFormatPattern().length() ? filter.filterString2.length() : Utils.getDateTimeFormatPattern().length();
                date2 = new SimpleDateFormat(Utils.getDateTimeFormatPattern().substring(0, length)).parse(filter.filterString2);
            }
            criterion = Restrictions.between(filter.getPropertyId().toString(), date1, date2);
        } catch (ParseException e) {
            Date date1 = new Date(1);
            Date date2 = new Date(2);
            criterion = Restrictions.between(filter.getPropertyId().toString(), date2, date1);
        }
    } else if (clazz.equals(Boolean.class)) {
        if (filter.filterString.equalsIgnoreCase(Constants.uiYes) || filter.filterString.equalsIgnoreCase(Constants.uiYes.substring(0, 1)) || filter.filterString.equals("1")) {
            criterion = Restrictions.eq(filter.getPropertyId().toString(), true);
        } else if (filter.filterString.equalsIgnoreCase(Constants.uiNo) || filter.filterString.equalsIgnoreCase(Constants.uiNo.substring(0, 1)) || filter.filterString.equals("0")) {
            criterion = Restrictions.eq(filter.getPropertyId().toString(), false);
        } else {
            // this should reject all results
            criterion = Restrictions.and(Restrictions.eq(filter.getPropertyId().toString(), true), Restrictions.eq(filter.getPropertyId().toString(), false));
        }
    }
    return criterion;
}
Example 71
Project: jspresso-ce-master  File: DefaultCriteriaFactory.java View source code
/**
   * Creates a like restriction.
   *
   * @param propertyDescriptor
   *     the property descriptor.
   * @param prefixedProperty
   *     the complete property path.
   * @param propertyValue
   *     the value to create the like restriction for
   * @param componentDescriptor
   *     the component descriptor
   * @param queryComponent
   *     the query component
   * @param context
   *     the context
   * @return the created criterion or null if no criterion necessary.
   */
protected Criterion createLikeRestriction(IPropertyDescriptor propertyDescriptor, String prefixedProperty, String propertyValue, IComponentDescriptor<?> componentDescriptor, IQueryComponent queryComponent, Map<String, Object> context) {
    MatchMode matchMode;
    if (propertyValue.contains("%")) {
        matchMode = MatchMode.EXACT;
    } else {
        matchMode = MatchMode.START;
    }
    if (propertyDescriptor instanceof IStringPropertyDescriptor && ((IStringPropertyDescriptor) propertyDescriptor).isUpperCase()) {
        // don't use ignoreCase() to be able to leverage indices.
        return Restrictions.like(prefixedProperty, propertyValue.toUpperCase(), matchMode);
    }
    return Restrictions.like(prefixedProperty, propertyValue, matchMode).ignoreCase();
}
Example 72
Project: Katari-master  File: KatariActivityService.java View source code
/** Creates a hibernate criteria for the provided conditions.
   *
   * This operation only considers the conditions that affect the number of
   * returned activities. The criteria is intended to be used to count the
   * number of matching activities and then add the sort conditions.
   *
   * @param userIds The user ids of the activities to search. It cannot be null.
   *
   * @param groupId only supports @self, that returns all the activities from
   * all the provided users. It cannot be null.
   *
   * @param appId The application id of activities. It cannot be null.
   *
   * @param options Options related to the resulting activities, like
   * filtering, etc. The returned criteria only contains the options that affect
   * the number or returned activities.. It cannot be null.
   *
   * @param token an opaque token that represents the logged in user. It cannot
   * be null.
   *
   * @return A criteria that matches the conditions inferred from the
   * parameters.
   */
private Criteria createCriteriaFor(final Set<UserId> userIds, final GroupId groupId, final String appId, final CollectionOptions options, final SecurityToken token) {
    log.trace("Entering createCriteriaFor");
    Validate.notNull(userIds, "The list of user ids cannot be null.");
    Validate.notNull(groupId, "The group id cannot be null.");
    Validate.notNull(options, "The options cannot be null.");
    Validate.notNull(token, "The security token cannot be null.");
    Validate.isTrue(options.getMax() > 0, "You should ask for at least one row.");
    Criteria criteria = getSession().createCriteria(Activity.class);
    addGroupFilterToCriteria(criteria, userIds, groupId, token, appId);
    if (!appId.equals(newsFeedApplicationId)) {
        Application app;
        app = applicationRepository.findApplicationByUrl(appId);
        criteria.add(Restrictions.eq("application", app));
    }
    if (options.getFilter() != null) {
        if (options.getFilterOperation() == null) {
            throw new ProtocolException(HttpServletResponse.SC_BAD_REQUEST, "If you request a filter, you must specify the filter operation.");
        } else if (options.getFilterOperation().equals(FilterOperation.present)) {
            criteria.add(Restrictions.isNotNull(options.getFilter()));
        } else {
            if (options.getFilterValue() == null) {
                throw new ProtocolException(HttpServletResponse.SC_BAD_REQUEST, "If you request a filter, you must specify the value.");
            }
            switch(options.getFilterOperation()) {
                case equals:
                    criteria.add(Restrictions.eq(options.getFilter(), options.getFilterValue()));
                    break;
                case startsWith:
                    criteria.add(Restrictions.like(options.getFilter(), options.getFilterValue(), MatchMode.START));
                    break;
                case present:
                    criteria.add(Restrictions.like(options.getFilter(), options.getFilterValue(), MatchMode.ANYWHERE));
                    break;
                default:
                    throw new RuntimeException("Unsupported filter operation " + options.getFilterOperation());
            }
        }
    }
    log.trace("Leaving createCriteriaFor");
    return criteria;
}
Example 73
Project: opennms_dashboard-master  File: NetworkElementFactory.java View source code
/* (non-Javadoc)
	 * @see org.opennms.web.element.NetworkElementFactoryInterface#getNodesLike(java.lang.String)
	 */
@Override
public List<OnmsNode> getNodesLike(String nodeLabel) {
    OnmsCriteria criteria = new OnmsCriteria(OnmsNode.class);
    criteria.createAlias("assetRecord", "assetRecord");
    criteria.add(Restrictions.and(Restrictions.ilike("label", nodeLabel, MatchMode.ANYWHERE), Restrictions.or(Restrictions.isNull("type"), Restrictions.ne("type", "D"))));
    criteria.addOrder(Order.asc("label"));
    return m_nodeDao.findMatching(criteria);
}
Example 74
Project: SOCIETIES-Platform-master  File: ServiceRegistry.java View source code
private Criteria createCriteriaFromService(Service filter, Session session) {
    Criteria c = session.createCriteria(RegistryEntry.class);
    // Direct Attributes
    if (filter.getServiceName() != null)
        c.add(Restrictions.like("serviceName", filter.getServiceName(), MatchMode.ANYWHERE));
    if (filter.getServiceDescription() != null)
        c.add(Restrictions.like("serviceDescription", filter.getServiceDescription(), MatchMode.ANYWHERE));
    if (filter.getAuthorSignature() != null)
        c.add(Restrictions.like("authorSignature", filter.getAuthorSignature(), MatchMode.ANYWHERE));
    if (filter.getPrivacyPolicy() != null)
        c.add(Restrictions.like("privacyPolicy", filter.getPrivacyPolicy()));
    if (filter.getSecurityPolicy() != null)
        c.add(Restrictions.like("securityPolicy", filter.getSecurityPolicy()));
    if (filter.getServiceCategory() != null)
        c.add(Restrictions.like("serviceCategory", filter.getServiceCategory(), MatchMode.ANYWHERE));
    if (filter.getServiceEndpoint() != null)
        c.add(Restrictions.like("serviceEndPoint", filter.getServiceEndpoint()));
    if (filter.getContextSource() != null)
        c.add(Restrictions.like("contextSource", filter.getContextSource()));
    if (filter.getServiceLocation() != null)
        c.add(Restrictions.like("serviceLocation", filter.getServiceLocation()));
    if (filter.getServiceStatus() != null)
        c.add(Restrictions.like("serviceStatus", filter.getServiceStatus().toString()));
    if (filter.getServiceType() != null)
        c.add(Restrictions.like("serviceType", filter.getServiceType().toString()));
    //Service Identifier
    ServiceResourceIdentifier servId = filter.getServiceIdentifier();
    if (servId != null) {
        //c.createAlias("serviceIdentifier", "sri");
        if (servId.getIdentifier() != null) {
            c.add(Restrictions.like("serviceIdentifier.identifier", servId.getIdentifier().toString()));
        }
        if (servId.getServiceInstanceIdentifier() != null) {
            c.add(Restrictions.like("serviceIdentifier.instanceId", servId.getServiceInstanceIdentifier()));
        }
    }
    //Service Instance
    ServiceInstance servInst = filter.getServiceInstance();
    if (servInst != null) {
        c.createAlias("serviceInstance", "servInst");
        if (servInst.getFullJid() != null) {
            c.add(Restrictions.like("servInst.fullJid", servInst.getFullJid()));
        }
        if (servInst.getCssJid() != null) {
            c.add(Restrictions.like("servInst.cssJid", servInst.getXMPPNode()));
        }
        if (servInst.getParentJid() != null) {
            c.add(Restrictions.like("servInst.parentJid", servInst.getXMPPNode()));
        }
        if (servInst.getXMPPNode() != null) {
            c.add(Restrictions.like("servInst.XMPPNode", servInst.getXMPPNode()));
        }
        ServiceResourceIdentifier pi = servInst.getParentIdentifier();
        if (pi != null) {
            c.createAlias("servInst.parentIdentifier", "parentId");
            if (pi.getIdentifier() != null) {
                c.add(Restrictions.like("parentId.identifier", pi.getIdentifier().toString()));
            }
            if (pi.getServiceInstanceIdentifier() != null) {
                c.add(Restrictions.like("parentId.instanceId", pi.getServiceInstanceIdentifier()));
            }
        }
        ServiceImplementation si = servInst.getServiceImpl();
        if (si != null) {
            c.createAlias("servInst.serviceImpl", "servImpl");
            if (si.getServiceNameSpace() != null) {
                c.add(Restrictions.like("servImpl.serviceNameSpace", si.getServiceNameSpace()));
            }
            if (si.getServiceProvider() != null) {
                c.add(Restrictions.like("servImpl.serviceProvider", si.getServiceProvider()));
            }
            if (si.getServiceVersion() != null) {
                c.add(Restrictions.like("servImpl.serviceVersion", si.getServiceVersion()));
            }
            if (si.getServiceClient() != null) {
                c.add(Restrictions.like("servImpl.serviceClient", si.getServiceVersion()));
            }
        }
    }
    return c;
}
Example 75
Project: clinic-softacad-master  File: FooBarTest.java View source code
@Test
public void testFindByCriteria() throws Exception {
    if (getDialect() instanceof DB2Dialect) {
        return;
    }
    Session s = openSession();
    Transaction txn = s.beginTransaction();
    Foo f = new Foo();
    s.save(f);
    s.flush();
    List list = s.createCriteria(Foo.class).add(Restrictions.eq("integer", f.getInteger())).add(Restrictions.eqProperty("integer", "integer")).add(Restrictions.like("string", f.getString().toUpperCase()).ignoreCase()).add(Restrictions.in("boolean", new Boolean[] { f.getBoolean(), f.getBoolean() })).setFetchMode("foo", FetchMode.JOIN).setFetchMode("baz", FetchMode.SELECT).setFetchMode("abstracts", FetchMode.JOIN).list();
    assertTrue(list.size() == 1 && list.get(0) == f);
    list = s.createCriteria(Foo.class).add(Restrictions.disjunction().add(Restrictions.eq("integer", f.getInteger())).add(Restrictions.like("string", f.getString())).add(Restrictions.eq("boolean", f.getBoolean()))).add(Restrictions.isNotNull("boolean")).list();
    assertTrue(list.size() == 1 && list.get(0) == f);
    Foo example = new Foo();
    example.setString("a STRing");
    list = s.createCriteria(Foo.class).add(Example.create(example).excludeZeroes().ignoreCase().excludeProperty("bool").excludeProperty("char").excludeProperty("yesno")).list();
    assertTrue("Example API without like did not work correctly, size was " + list.size(), list.size() == 1 && list.get(0) == f);
    example.setString("rin");
    list = s.createCriteria(Foo.class).add(Example.create(example).excludeZeroes().enableLike(MatchMode.ANYWHERE).excludeProperty("bool").excludeProperty("char").excludeProperty("yesno")).list();
    assertTrue("Example API without like did not work correctly, size was " + list.size(), list.size() == 1 && list.get(0) == f);
    list = s.createCriteria(Foo.class).add(Restrictions.or(Restrictions.and(Restrictions.eq("integer", f.getInteger()), Restrictions.like("string", f.getString())), Restrictions.eq("boolean", f.getBoolean()))).list();
    assertTrue(list.size() == 1 && list.get(0) == f);
    list = s.createCriteria(Foo.class).setMaxResults(5).addOrder(Order.asc("date")).list();
    assertTrue(list.size() == 1 && list.get(0) == f);
    list = s.createCriteria(Foo.class).setFirstResult(1).addOrder(Order.asc("date")).addOrder(Order.desc("string")).list();
    assertTrue(list.size() == 0);
    list = s.createCriteria(Foo.class).setFetchMode("component.importantDates", FetchMode.JOIN).list();
    assertTrue(list.size() == 3);
    list = s.createCriteria(Foo.class).setFetchMode("component.importantDates", FetchMode.JOIN).setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list();
    assertTrue(list.size() == 1);
    f.setFoo(new Foo());
    s.save(f.getFoo());
    txn.commit();
    s.close();
    s = openSession();
    txn = s.beginTransaction();
    list = s.createCriteria(Foo.class).add(Restrictions.eq("integer", f.getInteger())).add(Restrictions.like("string", f.getString())).add(Restrictions.in("boolean", new Boolean[] { f.getBoolean(), f.getBoolean() })).add(Restrictions.isNotNull("foo")).setFetchMode("foo", FetchMode.JOIN).setFetchMode("baz", FetchMode.SELECT).setFetchMode("component.glarch", FetchMode.SELECT).setFetchMode("foo.baz", FetchMode.SELECT).setFetchMode("foo.component.glarch", FetchMode.SELECT).list();
    f = (Foo) list.get(0);
    assertTrue(Hibernate.isInitialized(f.getFoo()));
    assertTrue(!Hibernate.isInitialized(f.getComponent().getGlarch()));
    s.save(new Bar());
    list = s.createCriteria(Bar.class).list();
    assertTrue(list.size() == 1);
    assertTrue(s.createCriteria(Foo.class).list().size() == 3);
    s.delete(list.get(0));
    s.delete(f.getFoo());
    s.delete(f);
    txn.commit();
    s.close();
}
Example 76
Project: hibernate-core-ogm-master  File: FooBarTest.java View source code
@Test
public void testFindByCriteria() throws Exception {
    if (getDialect() instanceof DB2Dialect) {
        return;
    }
    Session s = openSession();
    Transaction txn = s.beginTransaction();
    Foo f = new Foo();
    s.save(f);
    s.flush();
    List list = s.createCriteria(Foo.class).add(Restrictions.eq("integer", f.getInteger())).add(Restrictions.eqProperty("integer", "integer")).add(Restrictions.like("string", f.getString().toUpperCase()).ignoreCase()).add(Restrictions.in("boolean", new Boolean[] { f.getBoolean(), f.getBoolean() })).setFetchMode("foo", FetchMode.JOIN).setFetchMode("baz", FetchMode.SELECT).setFetchMode("abstracts", FetchMode.JOIN).list();
    assertTrue(list.size() == 1 && list.get(0) == f);
    list = s.createCriteria(Foo.class).add(Restrictions.disjunction().add(Restrictions.eq("integer", f.getInteger())).add(Restrictions.like("string", f.getString())).add(Restrictions.eq("boolean", f.getBoolean()))).add(Restrictions.isNotNull("boolean")).list();
    assertTrue(list.size() == 1 && list.get(0) == f);
    Foo example = new Foo();
    example.setString("a STRing");
    list = s.createCriteria(Foo.class).add(Example.create(example).excludeZeroes().ignoreCase().excludeProperty("bool").excludeProperty("char").excludeProperty("yesno")).list();
    assertTrue("Example API without like did not work correctly, size was " + list.size(), list.size() == 1 && list.get(0) == f);
    example.setString("rin");
    list = s.createCriteria(Foo.class).add(Example.create(example).excludeZeroes().enableLike(MatchMode.ANYWHERE).excludeProperty("bool").excludeProperty("char").excludeProperty("yesno")).list();
    assertTrue("Example API without like did not work correctly, size was " + list.size(), list.size() == 1 && list.get(0) == f);
    list = s.createCriteria(Foo.class).add(Restrictions.or(Restrictions.and(Restrictions.eq("integer", f.getInteger()), Restrictions.like("string", f.getString())), Restrictions.eq("boolean", f.getBoolean()))).list();
    assertTrue(list.size() == 1 && list.get(0) == f);
    list = s.createCriteria(Foo.class).setMaxResults(5).addOrder(Order.asc("date")).list();
    assertTrue(list.size() == 1 && list.get(0) == f);
    if (!(getDialect() instanceof TimesTenDialect || getDialect() instanceof HSQLDialect)) {
        list = s.createCriteria(Foo.class).setMaxResults(0).list();
        assertTrue(list.size() == 0);
    }
    list = s.createCriteria(Foo.class).setFirstResult(1).addOrder(Order.asc("date")).addOrder(Order.desc("string")).list();
    assertTrue(list.size() == 0);
    list = s.createCriteria(Foo.class).setFetchMode("component.importantDates", FetchMode.JOIN).list();
    assertTrue(list.size() == 3);
    list = s.createCriteria(Foo.class).setFetchMode("component.importantDates", FetchMode.JOIN).setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list();
    assertTrue(list.size() == 1);
    f.setFoo(new Foo());
    s.save(f.getFoo());
    txn.commit();
    s.close();
    s = openSession();
    txn = s.beginTransaction();
    list = s.createCriteria(Foo.class).add(Restrictions.eq("integer", f.getInteger())).add(Restrictions.like("string", f.getString())).add(Restrictions.in("boolean", new Boolean[] { f.getBoolean(), f.getBoolean() })).add(Restrictions.isNotNull("foo")).setFetchMode("foo", FetchMode.JOIN).setFetchMode("baz", FetchMode.SELECT).setFetchMode("component.glarch", FetchMode.SELECT).setFetchMode("foo.baz", FetchMode.SELECT).setFetchMode("foo.component.glarch", FetchMode.SELECT).list();
    f = (Foo) list.get(0);
    assertTrue(Hibernate.isInitialized(f.getFoo()));
    assertTrue(!Hibernate.isInitialized(f.getComponent().getGlarch()));
    s.save(new Bar());
    list = s.createCriteria(Bar.class).list();
    assertTrue(list.size() == 1);
    assertTrue(s.createCriteria(Foo.class).list().size() == 3);
    s.delete(list.get(0));
    s.delete(f.getFoo());
    s.delete(f);
    txn.commit();
    s.close();
}
Example 77
Project: hibernate-orm-master  File: FooBarTest.java View source code
@Test
public void testFindByCriteria() throws Exception {
    if (getDialect() instanceof DB2Dialect) {
        return;
    }
    Session s = openSession();
    Transaction txn = s.beginTransaction();
    Foo f = new Foo();
    s.save(f);
    s.flush();
    List list = s.createCriteria(Foo.class).add(Restrictions.eq("integer", f.getInteger())).add(Restrictions.eqProperty("integer", "integer")).add(Restrictions.like("string", f.getString().toUpperCase(Locale.ROOT)).ignoreCase()).add(Restrictions.in("boolean", f.getBoolean(), f.getBoolean())).setFetchMode("foo", FetchMode.JOIN).setFetchMode("baz", FetchMode.SELECT).setFetchMode("abstracts", FetchMode.JOIN).list();
    assertTrue(list.size() == 1 && list.get(0) == f);
    list = s.createCriteria(Foo.class).add(Restrictions.disjunction().add(Restrictions.eq("integer", f.getInteger())).add(Restrictions.like("string", f.getString())).add(Restrictions.eq("boolean", f.getBoolean()))).add(Restrictions.isNotNull("boolean")).list();
    assertTrue(list.size() == 1 && list.get(0) == f);
    Foo example = new Foo();
    example.setString("a STRing");
    list = s.createCriteria(Foo.class).add(Example.create(example).excludeZeroes().ignoreCase().excludeProperty("bool").excludeProperty("char").excludeProperty("yesno")).list();
    assertTrue("Example API without like did not work correctly, size was " + list.size(), list.size() == 1 && list.get(0) == f);
    example.setString("rin");
    list = s.createCriteria(Foo.class).add(Example.create(example).excludeZeroes().enableLike(MatchMode.ANYWHERE).excludeProperty("bool").excludeProperty("char").excludeProperty("yesno")).list();
    assertTrue("Example API without like did not work correctly, size was " + list.size(), list.size() == 1 && list.get(0) == f);
    list = s.createCriteria(Foo.class).add(Restrictions.or(Restrictions.and(Restrictions.eq("integer", f.getInteger()), Restrictions.like("string", f.getString())), Restrictions.eq("boolean", f.getBoolean()))).list();
    assertTrue(list.size() == 1 && list.get(0) == f);
    list = s.createCriteria(Foo.class).setMaxResults(5).addOrder(Order.asc("date")).list();
    assertTrue(list.size() == 1 && list.get(0) == f);
    list = s.createCriteria(Foo.class).setFirstResult(1).addOrder(Order.asc("date")).addOrder(Order.desc("string")).list();
    assertTrue(list.size() == 0);
    list = s.createCriteria(Foo.class).setFetchMode("component.importantDates", FetchMode.JOIN).list();
    assertTrue(list.size() == 3);
    list = s.createCriteria(Foo.class).setFetchMode("component.importantDates", FetchMode.JOIN).setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list();
    assertTrue(list.size() == 1);
    f.setFoo(new Foo());
    s.save(f.getFoo());
    txn.commit();
    s.close();
    s = openSession();
    txn = s.beginTransaction();
    list = s.createCriteria(Foo.class).add(Restrictions.eq("integer", f.getInteger())).add(Restrictions.like("string", f.getString())).add(Restrictions.in("boolean", f.getBoolean(), f.getBoolean())).add(Restrictions.isNotNull("foo")).setFetchMode("foo", FetchMode.JOIN).setFetchMode("baz", FetchMode.SELECT).setFetchMode("component.glarch", FetchMode.SELECT).setFetchMode("foo.baz", FetchMode.SELECT).setFetchMode("foo.component.glarch", FetchMode.SELECT).list();
    f = (Foo) list.get(0);
    assertTrue(Hibernate.isInitialized(f.getFoo()));
    assertTrue(!Hibernate.isInitialized(f.getComponent().getGlarch()));
    s.save(new Bar());
    list = s.createCriteria(Bar.class).list();
    assertTrue(list.size() == 1);
    assertTrue(s.createCriteria(Foo.class).list().size() == 3);
    s.delete(list.get(0));
    s.delete(f.getFoo());
    s.delete(f);
    txn.commit();
    s.close();
}
Example 78
Project: jtrac-master  File: HibernateJtracDao.java View source code
public List<User> findUsersMatching(final String searchText, final String searchOn) {
    return (List<User>) getHibernateTemplate().execute(new HibernateCallback() {

        public Object doInHibernate(Session session) {
            Criteria criteria = session.createCriteria(User.class);
            criteria.add(Restrictions.ilike(searchOn, searchText, MatchMode.ANYWHERE));
            criteria.addOrder(Order.asc("name"));
            return criteria.list();
        }
    });
}
Example 79
Project: squale-master  File: AbstractDAOImpl.java View source code
/**
     * Execute un find a partir d'un objet exemple
     * 
     * @param session session de persistance
     * @param bo businness object exemple
     * @param nbLignes nombre de lignes
     * @param indexDepart index de depart
     * @param ignoreCase ignore la casse
     * @param likeMode mode like
     * @param cache true si les elements retournes sont mis en cache, false sinon
     * @return liste d'objets retrouves
     * @throws JrafDaoException
     */
public List findByExample(ISession session, Object bo, int nbLignes, int indexDepart, boolean ignoreCase, boolean likeMode, boolean cache, int matchMode) throws JrafDaoException {
    SessionImpl sessionImpl = (SessionImpl) session;
    Criteria crit = sessionImpl.getSession().createCriteria(bo.getClass());
    Example example = Example.create(bo);
    // ignore la casse
    if (ignoreCase) {
        example.ignoreCase();
    }
    // mode like
    if (likeMode) {
        switch(matchMode) {
            case 0:
                example.enableLike(MatchMode.START);
                break;
            case 1:
                example.enableLike(MatchMode.END);
                break;
            default:
                example.enableLike(MatchMode.ANYWHERE);
                break;
        }
    }
    // ajout de l'example
    crit.add(example);
    if (indexDepart > -1) {
        crit.setFirstResult(indexDepart);
    }
    if (nbLignes > 0) {
        crit.setMaxResults(nbLignes);
    }
    crit.setCacheable(cache);
    List l = null;
    try {
        l = crit.list();
    } catch (HibernateException e) {
        throwDAOException(e, "findByExample");
    }
    return l;
}
Example 80
Project: exit-web-framework-master  File: LikeRestriction.java View source code
public Criterion build(String propertyName, Object value) {
    return Restrictions.like(propertyName, value.toString(), MatchMode.ANYWHERE);
}
Example 81
Project: kickr-master  File: PlayerDAO.java View source code
@SuppressWarnings("unchecked")
public List<Player> findPlayersMatchingNameOrAlias(String part) {
    return criteria().add(Restrictions.or(Restrictions.ilike("name", part, MatchMode.ANYWHERE), Restrictions.ilike("alias", part, MatchMode.ANYWHERE))).list();
}
Example 82
Project: bbsys-master  File: UsuarioDao.java View source code
@SuppressWarnings("unchecked")
public List<Usuario> busca(String nome) {
    return session.createCriteria(Usuario.class).add(Restrictions.ilike("name", nome, MatchMode.ANYWHERE)).list();
}
Example 83
Project: gxt-tools-master  File: WsecPermissionDaoImpl.java View source code
public List<WsecPermission> fetchSystemPermissions() {
    List<WsecPermission> result = getHibernateTemplate().findByCriteria(DetachedCriteria.forClass(WsecPermission.class).add(Restrictions.like("name", "WSEC_", MatchMode.START)));
    return result;
}
Example 84
Project: liquid-democracy-master  File: AbstractDao.java View source code
@SuppressWarnings("unchecked")
public List<T> findByName(String name) {
    Criteria criteria = getSession().createCriteria(clazz.getName());
    criteria.add(Restrictions.ilike("name", name.toUpperCase(), MatchMode.START));
    return criteria.list();
}
Example 85
Project: encontreaquipecas-master  File: UsuarioRepository.java View source code
@SuppressWarnings("unchecked")
public List<Usuario> findAllByLogin(String login) {
    Criteria criteria = getSession().createCriteria(Usuario.class);
    criteria.add(Restrictions.ilike("login", login, MatchMode.ANYWHERE));
    return criteria.addOrder(Order.asc("nome")).list();
}
Example 86
Project: niths-master  File: AbstractGenericRepositoryImpl.java View source code
/**
     * Find and returns all objects which has values equal to the object sent as
     * parameter.
     * 
     * @param domain
     *            - The object that has the values to search for
     * @return List of objects found
     */
@SuppressWarnings("unchecked")
public List<T> getAll(T domain) {
    return buildCriteria(domain, MatchMode.ANYWHERE).list();
}
Example 87
Project: generic-dao-hibernate-master  File: ReadableDAOImpl.java View source code
/**
	 * Used by {@link #findByExample(Object)} to create an {@link Example} instance.
	 * 
	 * @todo add criteria for property types not handled by Example (primary keys, associations,
	 * etc)
	 * @return an {@link Example}.
	 */
public Example createExample(T entity) {
    Example example = Example.create(entity);
    example.enableLike(MatchMode.ANYWHERE);
    example.excludeZeroes();
    example.ignoreCase();
    return example;
}
Example 88
Project: jforum3-master  File: UserRepository.java View source code
/**
	 * Find a set of users who match an input
	 * @param username the search input
	 * @return the list of users matching the search input
	 */
@SuppressWarnings("unchecked")
public List<User> findByUserName(String username) {
    return session.createCriteria(this.persistClass).add(Restrictions.ilike("username", username, MatchMode.ANYWHERE)).addOrder(Order.asc("username")).setComment("userDAO.findByUsername").list();
}
Example 89
Project: obiba-commons-master  File: AssociationExample.java View source code
/**
   * Use the "like" operator for all string-valued properties
   */
public AssociationExample enableLike(@SuppressWarnings("ParameterHidesMemberVariable") MatchMode matchMode) {
    isLikeEnabled = true;
    this.matchMode = matchMode;
    return this;
}
Example 90
Project: tocollege.net-master  File: SchoolDAOHibernateImpl.java View source code
public List<School> getSchoolsMatching(String match) {
    return getSchoolsMatching(match, 0, autoCompleteMax, MatchMode.ANYWHERE);
}
Example 91
Project: cosmocode-hibernate-master  File: CustomRestrictions.java View source code
/**
     * Apply an "ilike" constraint on the named property.
     * 
     * <p>
     *   Note: This implementation differs from {@link Restrictions#ilike(String, String, MatchMode)}
     *   because it checks for empty strings and applies {@link CustomRestrictions#isEmpty(String)}
     *   instead.
     * </p>
     * 
     * @param propertyName the name of the property the constraint should be applied to
     * @param value the actual value the property should be similiar to
     * @param matchMode the {@link MatchMode} being used
     * @return a new {@link Criterion}
     */
public static Criterion ilike(String propertyName, String value, MatchMode matchMode) {
    return StringUtils.isEmpty(value) ? CustomRestrictions.isEmpty(propertyName) : Restrictions.ilike(propertyName, value, matchMode);
}
Example 92
Project: hq-master  File: ResourceEdgeDAO.java View source code
List<ResourceEdge> findByName(String name, ResourceRelation relation) {
    return getSession().createCriteria(ResourceEdge.class).createAlias("from", "f").add(Restrictions.ilike("f.name", name, MatchMode.ANYWHERE)).add(Restrictions.eq("relation", relation)).add(Restrictions.eq("distance", new Integer(0))).list();
}
Example 93
Project: AIDR-master  File: CollectionRepositoryImpl.java View source code
@SuppressWarnings("unchecked")
@Override
public List<Collection> searchByName(String query, Long userId) throws Exception {
    Criteria criteria = getHibernateTemplate().getSessionFactory().getCurrentSession().createCriteria(Collection.class);
    criteria.add(Restrictions.ilike("name", query, MatchMode.ANYWHERE));
    criteria.add(Restrictions.eq("owner.id", userId));
    return criteria.list();
}
Example 94
Project: qcadoo-master  File: SearchRestrictions.java View source code
public MatchMode getHibernateMatchMode() {
    return matchMode;
}
Example 95
Project: buendia-master  File: HibernateSyncDAO.java View source code
@SuppressWarnings("unchecked")
public List<SyncRecord> getSyncRecords(String query) throws DAOException {
    return sessionFactory.getCurrentSession().createCriteria(SyncRecord.class).add(Expression.or(Restrictions.like("items", query, MatchMode.ANYWHERE), Restrictions.eq("originalUuid", query))).addOrder(Order.desc("timestamp")).setMaxResults(// max number of records returned
    250).list();
}