Example usage for org.hibernate.criterion Restrictions in

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

Introduction

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

Prototype

public static Criterion in(String propertyName, Collection values) 

Source Link

Document

Apply an "in" constraint to the named property.

Usage

From source file:com.jaspersoft.jasperserver.api.metadata.user.service.impl.UserAuthorityServiceImpl.java

License:Open Source License

private void addTenantCriteria(Criteria criteria, Set tenantIds) {
    Set internalTenantIds = null;
    if (tenantIds != null) {
        internalTenantIds = new HashSet();
        internalTenantIds.addAll(tenantIds);
        if (internalTenantIds.contains(null)) {
            internalTenantIds.remove(null);
            internalTenantIds.add(TenantService.ORGANIZATIONS);
        }// ww w  . j a v a2s. com
    }
    criteria.createAlias("tenant", "tenant", Criteria.LEFT_JOIN);
    if (internalTenantIds == null) {
        criteria.add(Restrictions.eq("tenant.tenantId", TenantService.ORGANIZATIONS));
    } else {
        if (!internalTenantIds.isEmpty()) {
            Criterion idInCriterion = Restrictions.in("tenant.tenantId", internalTenantIds);
            criteria.add(idInCriterion);
        }
    }
}

From source file:com.jaspersoft.jasperserver.api.metadata.user.service.impl.UserAuthorityServiceImpl.java

License:Open Source License

protected List getIdByTenantIdSet(Set tenantIds) {
    DetachedCriteria idCriteria = DetachedCriteria.forClass(getPersistentTenantClass());
    idCriteria.add(Restrictions.in("tenantId", tenantIds));
    idCriteria.setProjection(Projections.id());
    return getHibernateTemplate().findByCriteria(idCriteria);
}

From source file:com.jaspersoft.jasperserver.api.metadata.user.service.impl.UserAuthorityServiceImpl.java

License:Open Source License

protected void addVisibleTenantCriteria(DetachedCriteria criteria, Set tenantIds) {
    Set internalTenantIds = null;
    if (tenantIds != null) {
        internalTenantIds = new HashSet();
        internalTenantIds.addAll(tenantIds);
        if (internalTenantIds.contains(null)) {
            internalTenantIds.remove(null);
            internalTenantIds.add(TenantService.ORGANIZATIONS);
        }/*from w w w .ja  v a2 s .  c o m*/
    }
    if (internalTenantIds == null) {
        RepoTenant tenant = tenantPersistenceResolver.getPersistentTenant(TenantService.ORGANIZATIONS, true);
        criteria.add(Restrictions.eq("tenant.id", tenant.getId()));
    } else {
        if (!internalTenantIds.isEmpty()) {
            Criterion idInCriterion = Restrictions.in("tenant.id", getIdByTenantIdSet(internalTenantIds));
            criteria.add(idInCriterion);
        }
    }
}

From source file:com.jaspersoft.jasperserver.api.metadata.user.service.impl.UserAuthorityServiceImpl.java

License:Open Source License

protected List getUsersByUserNames(ExecutionContext context, Set userNames) {
    DetachedCriteria criteria = DetachedCriteria.forClass(getPersistentUserClass());

    if (userNames != null && !userNames.isEmpty()) {

        criteria.add(Restrictions.in("username", userNames));
    }//from  w  w  w  .j  a v  a2s .  co m

    return getHibernateTemplate().findByCriteria(criteria);
}

From source file:com.jaspersoft.jasperserver.search.filter.ResourceTypeFilter.java

License:Open Source License

public void applyRestrictions(String type, ExecutionContext context, SearchCriteria criteria) {
    SearchAttributes searchAttributes = getSearchAttributes(context);

    if (searchAttributes != null && searchAttributes.getState() != null) {
        String resourceTypeFilterOption = searchAttributes.getState().getCustomFiltersMap()
                .get("resourceTypeFilter");

        List<String> resourceTypes = null;
        if (resourceTypeFilterOption != null) {
            resourceTypes = filterOptionToResourceTypes.get(resourceTypeFilterOption);
        }/*from   www  .j  a  v  a  2  s  . co  m*/

        if (resourceTypes != null) {
            criteria.add(Restrictions.in("resourceType", resourceTypes));
        }
    } else {
        final RepositorySearchCriteria repositorySearchCriteria = getTypedAttribute(context,
                RepositorySearchCriteria.class);
        if (repositorySearchCriteria != null) {
            if (repositorySearchCriteria.getResourceTypes() != null
                    && !repositorySearchCriteria.getResourceTypes().isEmpty()) {
                List<String> types = new ArrayList<String>(repositorySearchCriteria.getResourceTypes());
                boolean addFolders = types.remove(Folder.class.getName());
                Criterion criterion = Restrictions.in("resourceType", types);

                if (addFolders && ResourceLookup.class.getName().equals(type)) {
                    Criterion folderCriterion = Restrictions.isNull("resourceType");
                    criteria.add(
                            types.isEmpty() ? folderCriterion : Restrictions.or(folderCriterion, criterion));
                } else {
                    criteria.add(criterion);
                }
            }
        } else {
            throw new RuntimeException("Resource type filter not found in the custom filters map.");
        }
    }
}

From source file:com.jaspersoft.jasperserver.search.filter.ScheduleFilter.java

License:Open Source License

private void createCriteria(SearchCriteria criteria, User user, boolean scheduled, boolean scheduledByUser) {
    SearchCriteria uriCriteria = SearchCriteria.forClass(PersistentReportJob.class);
    if (scheduledByUser) {
        addOwnerCriteria(uriCriteria, user);
    }//ww w  . j  a v  a  2 s. co m
    uriCriteria.addProjection(Projections.property("source.reportUnitURI"));
    List uriList = getHibernateTemplate().findByCriteria(uriCriteria);

    if (!uriList.isEmpty()) {
        SearchCriteria idCriteria = SearchCriteria.forClass(RepoResource.class);
        Disjunction disjunction = Restrictions.disjunction();
        String alias = idCriteria.getAlias("parent", "p");
        for (Object o : uriList) {
            String uri = (String) o;

            disjunction.add(getResourceCriterion(alias, uri));
        }

        idCriteria.add(disjunction);
        idCriteria.addProjection(Projections.id());

        List idList = getHibernateTemplate().findByCriteria(idCriteria);

        if (!idList.isEmpty()) {
            if (scheduled) {
                criteria.add(Restrictions.in("id", idList));
            } else {
                criteria.add(Restrictions.not(Restrictions.in("id", idList)));
            }
        } else {
            throw new RuntimeException("No resources found for URI list " + uriList);
        }
    } else {
        if (scheduled || scheduledByUser) {
            criteria.add(Restrictions.isNull("id"));
        }
    }
}

From source file:com.jredrain.dao.HibernateDao.java

License:Apache License

public <T, K extends Serializable> List<T> getByIds(Class<T> entityClass, List<K> ids) {
    entityClass = getEntityClass(entityClass);
    String idName = getClassMetadata(entityClass).getIdentifierPropertyName();
    return createCriteria(entityClass).add(Restrictions.in(idName, ids)).list();
}

From source file:com.klistret.cmdb.utility.hibernate.XPathCriteria.java

License:Open Source License

/**
 * /*w  ww . j a v  a2 s .co  m*/
 * @param predicate
 * @return
 */
protected Criterion getRestriction(Expr predicate, HibernateStep context) {
    logger.debug("Adding restrictions by predicate to context [{}]", context);

    switch (predicate.getType()) {
    case Or:
        /**
         * Recursively breaks down the OrExpr by translating on the first
         * and second operands
         */
        if (((OrExpr) predicate).getOperands().size() != 2)
            throw new ApplicationException(
                    String.format("OrExpr expression [%s] expects 2 operands", predicate));

        return Restrictions.or(getRestriction(((OrExpr) predicate).getOperands().get(0), context),
                getRestriction(((OrExpr) predicate).getOperands().get(1), context));
    case And:
        /**
         * Recursively breaks down the AndExpr by translating on the first
         * and second operands
         */
        if (((AndExpr) predicate).getOperands().size() != 2)
            throw new ApplicationException(
                    String.format("AndExpr expression [%s] expects 2 operands", predicate));

        return Restrictions.and(getRestriction(((AndExpr) predicate).getOperands().get(0), context),
                getRestriction(((AndExpr) predicate).getOperands().get(1), context));
    case Comparison:
        /**
         * Find the literal
         */
        LiteralExpr literal = getLiteralOperand(((ComparisonExpr) predicate).getOperands());

        /**
         * Find the relative path making a Hibernate relative path
         */
        RelativePathExpr rpe = getRelativePathOperand(((ComparisonExpr) predicate).getOperands());
        HibernateRelativePath hRPath = process(rpe, context);
        build(hRPath);

        HibernateStep last = hRPath.getLastHibernateStep();

        /**
         * Property name with alias prefix
         */
        String alias = last.getPrevious() == null ? aliasCache.get(context.getPath())
                : aliasCache.get(last.getPrevious().getPath());
        String propertyName = alias == null ? last.getName() : String.format("%s.%s", alias, last.getName());

        /**
         * Paths with XML properties (always the last step if present)
         * return a XPath restriction.
         */
        if (hRPath.hasXML()) {
            if (!hRPath.isTruncated())
                throw new ApplicationException(String.format(
                        "Predicate relative path ending in an XML property [%s] must be truncated", last));

            /**
             * Last Hibernate step of the Hibernate path marks the property
             * which the restriction acts on.
             */
            StepExpr step = (StepExpr) last.getStep();

            /**
             * A new XPath is created from the last step downwards till the
             * step prior to the ending step.
             */
            String xpath = null;
            for (int depth = step.getDepth(); depth < step.getRelativePath().getDepth() - 1; depth++) {
                Expr expr = step.getRelativePath().getExpr(depth);
                xpath = xpath == null ? expr.getXPath() : String.format("%s/%s", xpath, expr.getXPath());
            }

            Step ending = (Step) step.getRelativePath().getLastExpr();

            /**
             * A new comparison is generated
             */
            List<Expr> operands = new ArrayList<Expr>();
            operands.add(ending);
            operands.add(literal);

            xpath = String.format("%s[%s]", xpath,
                    ComparisonExpr.getXPath(((ComparisonExpr) predicate).getOperator(), operands, false));
            xpath = String.format("%s%s", context.getBaseExpression().getProlog(), xpath);

            PathExpression other = new PathExpression(xpath);
            return new XPathRestriction(propertyName, (Step) other.getRelativePath().getFirstExpr());
        }

        if (((StepExpr) last.getStep()).hasPredicates())
            throw new ApplicationException(String.format(
                    "Comparisons against Hibernate properties may not have an underlying step [] with predicates",
                    last.getStep()));

        logger.debug("Predicate is comparison [{}] against property [{}]",
                ((ComparisonExpr) predicate).getOperator().name(), propertyName);

        switch (((ComparisonExpr) predicate).getOperator()) {
        case ValueEquals:
            logger.debug("Value: {}", literal.getValue().getJavaValue());
            return Restrictions.eq(propertyName, literal.getValue().getJavaValue());
        case ValueGreaterThan:
            logger.debug("Value: {}", literal.getValue().getJavaValue());
            return Restrictions.gt(propertyName, literal.getValue().getJavaValue());
        case ValueGreaterThanOrEquals:
            logger.debug("Value: {}", literal.getValue().getJavaValue());
            return Restrictions.ge(propertyName, literal.getValue().getJavaValue());
        case ValueLessThan:
            logger.debug("Value: {}", literal.getValue().getJavaValue());
            return Restrictions.lt(propertyName, literal.getValue().getJavaValue());
        case ValueLessThanOrEquals:
            logger.debug("Value: {}", literal.getValue().getJavaValue());
            return Restrictions.le(propertyName, literal.getValue().getJavaValue());
        case ValueNotEquals:
            logger.debug("Value: {}", literal.getValue().getJavaValue());
            return Restrictions.ne(propertyName, literal.getValue().getJavaValue());
        case GeneralEquals:
            /**
             * If atomic (not a sequence) then the 'in' restriction is not
             * usable (defaults to 'eq' restriction) since the argument is
             * an array of objects.
             */
            if (literal.isAtomic()) {
                logger.debug("Value: {}", literal.getValue().getJavaValue());
                return Restrictions.eq(propertyName, literal.getValue().getJavaValue());
            }

            logger.debug("Values: {}", literal.getValues());

            Object[] javaValues = new Object[literal.getValues().length];
            for (int index = 0; index < literal.getValues().length; index++)
                javaValues[index] = ((com.klistret.cmdb.utility.saxon.Value) literal.getValues()[index])
                        .getJavaValue();

            return Restrictions.in(propertyName, javaValues);
        case Matches:
            if (((ComparisonExpr) predicate).getOperands().size() != 2)
                throw new ApplicationException(
                        String.format("Matches function [%s] expects 2 operands", predicate));

            logger.debug("Value: {}", literal.getValue().getText());
            return Restrictions.ilike(propertyName, literal.getValue().getText(), MatchMode.EXACT);
        case Exists:
            if (((ComparisonExpr) predicate).getOperands().size() != 1)
                throw new ApplicationException(
                        String.format("Exists function [%s] expects only 1 operand", predicate));

            return Restrictions.isNotNull(propertyName);
        case Empty:
            if (((ComparisonExpr) predicate).getOperands().size() != 1)
                throw new ApplicationException(
                        String.format("Empty function [%s] expects only 1 operand", predicate));

            return Restrictions.isNull(propertyName);
        default:
            throw new ApplicationException(
                    String.format("Unexpected comparison operator [%s] handling predicates",
                            ((ComparisonExpr) predicate).getOperator()));
        }

    default:
        throw new ApplicationException(String.format("Unexpected expr [%s] type for predicate", predicate));
    }
}

From source file:com.kodemore.hibernate.criteria.KmAbstractCriteria.java

License:Open Source License

public void addIsIn(String property, Object[] v) {
    if (v == null || v.length == 0)
        addFalse();/*from www.  j a  v a  2 s . com*/
    else
        _add(Restrictions.in(property, v));
}

From source file:com.kodemore.hibernate.criteria.KmAbstractCriteria.java

License:Open Source License

public void addIsIn(String property, Collection<?> v) {
    if (v == null || v.isEmpty())
        addFalse();//from ww  w . ja  v  a2  s.  c  o  m
    else
        _add(Restrictions.in(property, v));
}