Example usage for org.hibernate.criterion Restrictions not

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

Introduction

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

Prototype

public static Criterion not(Criterion expression) 

Source Link

Document

Return the negation of an expression

Usage

From source file:com.eucalyptus.vm.VmControl.java

License:Open Source License

public DescribeInstanceStatusResponseType describeInstanceStatus(final DescribeInstanceStatusType msg)
        throws EucalyptusCloudException {
    final DescribeInstanceStatusResponseType reply = (DescribeInstanceStatusResponseType) msg.getReply();
    final Context ctx = Contexts.lookup();
    final boolean showAll = msg.getInstancesSet().remove("verbose");
    final boolean includeAllInstances = Objects.firstNonNull(msg.getIncludeAllInstances(), Boolean.FALSE);
    final Collection<String> identifiers = normalizeIdentifiers(msg.getInstancesSet());
    final Filter filter = Filters.generateFor(msg.getFilterSet(), VmInstance.class, "status")
            .withOptionalInternalFilter("instance-id", identifiers).generate();
    final Predicate<? super VmInstance> requestedAndAccessible = CloudMetadatas.filteringFor(VmInstance.class)
            .byId(identifiers) // filters without wildcard support
            .byPredicate(includeAllInstances ? Predicates.<VmInstance>alwaysTrue() : VmState.RUNNING)
            .byPredicate(filter.asPredicate()).byPrivileges().buildPredicate();
    final Criterion criterion = filter
            .asCriterionWithConjunction(Restrictions.not(VmInstances.criterion(VmState.BURIED)));
    final OwnerFullName ownerFullName = (ctx.isAdministrator() && showAll) ? null
            : ctx.getUserFullName().asAccountFullName();
    try {/*  w  w  w .  j a va2s  .c  om*/
        final List<VmInstance> instances = VmInstances.list(ownerFullName, criterion, filter.getAliases(),
                requestedAndAccessible);

        Iterables.addAll(reply.getInstanceStatusSet().getItem(), Iterables.transform(instances,
                TypeMappers.lookup(VmInstance.class, InstanceStatusItemType.class)));

    } catch (final Exception e) {
        LOG.error(e);
        LOG.debug(e, e);
        throw new EucalyptusCloudException(e.getMessage());
    }
    return reply;
}

From source file:com.evolveum.midpoint.repo.sql.query.restriction.NotRestriction.java

License:Apache License

@Override
public Criterion interpret(NotFilter filter) throws QueryException {
    validateFilter(filter);//  w  w  w  . j  a  va 2 s .c o m
    Criterion criterion = interpretChildFilter(filter.getFilter());

    return Restrictions.not(criterion);
}

From source file:com.evolveum.midpoint.repo.sql.SqlRepositoryServiceImpl.java

License:Apache License

private List<RObject> deleteTransitiveHierarchy(RObject rObjectToModify, Session session)
        throws SchemaException, DtoTranslationException {

    Criteria cDescendant = session.createCriteria(ROrgClosure.class)
            .setProjection(Projections.property("descendant"))
            .add(Restrictions.eq("ancestor", rObjectToModify));

    Criteria cAncestor = session.createCriteria(ROrgClosure.class)
            .setProjection(Projections.property("ancestor")).createCriteria("ancestor", "anc")
            .add(Restrictions.and(Restrictions.eq("this.descendant", rObjectToModify),
                    Restrictions.not(Restrictions.eq("anc.oid", rObjectToModify.getOid()))));

    Criteria cOrgClosure = session.createCriteria(ROrgClosure.class);

    List<RObject> ocAncestor = cAncestor.list();
    List<RObject> ocDescendant = cDescendant.list();

    if (ocAncestor != null && !ocAncestor.isEmpty()) {
        cOrgClosure.add(Restrictions.in("ancestor", ocAncestor));
    } else {//w  w  w.j  a v a 2  s  .  c o m
        LOGGER.trace("No ancestors for object: {}", rObjectToModify.getOid());
    }

    if (ocDescendant != null && !ocDescendant.isEmpty()) {
        cOrgClosure.add(Restrictions.in("descendant", ocDescendant));
    } else {
        LOGGER.trace("No descendants for object: {}", rObjectToModify.getOid());
    }

    List<ROrgClosure> orgClosure = cOrgClosure.list();

    for (ROrgClosure o : orgClosure) {
        if (LOGGER.isTraceEnabled()) {
            RObject ancestor = o.getAncestor();
            RObject descendant = o.getDescendant();
            LOGGER.trace("deleting from hierarchy: A:{} D:{} depth:{}", new Object[] {
                    RUtil.getDebugString(ancestor), RUtil.getDebugString(descendant), o.getDepth() });
        }
        session.delete(o);
    }
    deleteHierarchy(rObjectToModify, session);
    return ocDescendant;
}

From source file:com.gisgraphy.domain.repository.GenericGisDao.java

License:Open Source License

/**
 * base method for all findNearest* /*from  w  ww . j ava2  s.c  om*/
 * 
 * @param point
 *                The point from which we want to find GIS Object
 * @param pointId
 *                the id of the point that we don't want to be include, it
 *                is used to not include the gisFeature from which we want
 *                to find the nearest
 * @param distance
 *                distance The radius in meters
 * @param firstResult
 *                the firstResult index (for pagination), numbered from 1,
 *                if < 1 : it will not be taken into account
 * @param maxResults
 *                The Maximum number of results to retrieve (for
 *                pagination), if <= 0 : it will not be taken into acount
 * @param requiredClass
 *                the class of the object to be retireved
 * @param isMunicipality whether we should filter on city that are flag as 'municipality'.
          act as a filter, if false it doesn't filters( false doesn't mean that we return non municipality)
 * @return A List of GisFeatureDistance with the nearest elements or an
 *         emptylist (never return null), ordered by distance.<u>note</u>
 *         the specified gisFeature will not be included into results
 * @see GisFeatureDistance
 * @return a list of gisFeature (never return null but an empty list)
 */
@SuppressWarnings("unchecked")
protected List<GisFeatureDistance> getNearestAndDistanceFrom(final Point point, final Long pointId,
        final double distance, final int firstResult, final int maxResults, final boolean includeDistanceField,
        final Class<? extends GisFeature> requiredClass, final boolean isMunicipality) {
    Assert.notNull(point);
    return (List<GisFeatureDistance>) this.getHibernateTemplate().execute(new HibernateCallback() {

        public Object doInHibernate(Session session) throws PersistenceException {
            Criteria criteria = session.createCriteria(requiredClass);

            if (maxResults > 0) {
                criteria = criteria.setMaxResults(maxResults);
            }
            if (firstResult >= 1) {
                criteria = criteria.setFirstResult(firstResult - 1);
            }
            criteria = criteria.add(new DistanceRestriction(point, distance));
            List<String> fieldList = IntrospectionHelper.getFieldsAsList(requiredClass);
            ProjectionList projections = ProjectionBean.fieldList(fieldList, true);
            if (includeDistanceField) {
                projections.add(SpatialProjection.distance_sphere(point, GisFeature.LOCATION_COLUMN_NAME)
                        .as("distance"));
            }
            criteria.setProjection(projections);
            if (pointId != 0) {
                // remove The From Point
                criteria = criteria.add(Restrictions.not(Restrictions.idEq(pointId)));
            }
            if (includeDistanceField) {
                criteria.addOrder(new ProjectionOrder("distance"));
            }
            if (isMunicipality && (requiredClass == City.class || requiredClass == GisFeature.class)) {
                criteria.add(Restrictions.eq(City.MUNICIPALITY_FIELD_NAME, isMunicipality));
            }

            criteria.setCacheable(true);
            List<Object[]> queryResults = criteria.list();

            String[] aliasList;
            if (includeDistanceField) {
                aliasList = (String[]) ArrayUtils.add(IntrospectionHelper.getFieldsAsArray(requiredClass),
                        "distance");
            } else {
                aliasList = IntrospectionHelper.getFieldsAsArray(requiredClass);
            }
            int idPropertyIndexInAliasList = 0;
            for (int i = 0; i < aliasList.length; i++) {
                if (aliasList[i] == "id") {
                    idPropertyIndexInAliasList = i;
                    break;
                }
            }

            boolean hasZipCodesProperty = ZipCodesAware.class.isAssignableFrom(requiredClass);
            Map<Long, Set<String>> idToZipCodesMap = null;
            if (hasZipCodesProperty && queryResults.size() > 0) {
                List<Long> ids = new ArrayList<Long>();
                for (Object[] tuple : queryResults) {
                    ids.add((Long) tuple[idPropertyIndexInAliasList]);
                }
                String zipCodeQuery = "SELECT code as code,gisfeature as id FROM "
                        + ZipCode.class.getSimpleName().toLowerCase() + " zip where zip.gisfeature in (:ids)";
                Query qry = session.createSQLQuery(zipCodeQuery).addScalar("code", Hibernate.STRING)
                        .addScalar("id", Hibernate.LONG);
                qry.setCacheable(true);

                qry.setParameterList("ids", ids);
                List<Object[]> zipCodes = (List<Object[]>) qry.list();

                if (zipCodes.size() > 0) {
                    idToZipCodesMap = new HashMap<Long, Set<String>>();
                    for (Object[] zipCode : zipCodes) {
                        Long idFromZipcode = (Long) zipCode[1];
                        Set<String> zipCodesFromMap = idToZipCodesMap.get(idFromZipcode);
                        if (zipCodesFromMap == null) {
                            Set<String> zipCodesToAdd = new HashSet<String>();
                            idToZipCodesMap.put(idFromZipcode, zipCodesToAdd);
                            zipCodesFromMap = zipCodesToAdd;
                        }
                        zipCodesFromMap.add((String) zipCode[0]);
                    }
                }
            }
            List<GisFeatureDistance> results = ResultTransformerUtil.transformToGisFeatureDistance(aliasList,
                    queryResults, idToZipCodesMap, requiredClass);
            return results;
        }
    });

}

From source file:com.globalsight.everest.usermgr.UserManagerLocal.java

License:Apache License

/**
 * @see UserManager.getUserInfos(String)
 */// w  ww  .  j  a  va 2 s. co m
public List getUserInfos(String[] p_userIds) throws RemoteException, UserManagerException {
    List uIds = new ArrayList();
    for (String uId : p_userIds) {
        uIds.add(uId);
    }

    Session session = HibernateUtil.getSession();

    boolean filterUser = false;

    Criteria c = session.createCriteria(UserImpl.class);
    c.add(Restrictions.in("userId", uIds));
    c.add(Restrictions.not(Restrictions.eq("state", User.State.DEACTIVE)));
    c.add(Restrictions.not(Restrictions.eq("state", User.State.DELETED)));

    List<UserImpl> us = c.list();
    List userInfos = new ArrayList();
    for (UserImpl u : us) {
        userInfos.add(u.toUserInfo());
    }

    return userInfos;
}

From source file:com.heliosapm.aa4h.parser.XMLQueryParser.java

License:Apache License

/**
 * Element Start SAX ContentHandler Method.
 * @param uri//from w ww  .  j a  v a 2  s .co m
 * @param localName
 * @param qName
 * @see org.xml.sax.ContentHandler#startElement(java.lang.String, java.lang.String, java.lang.String, org.xml.sax.Attributes)
 * @throws SAXException
 * TODO: Document supported tags in javadoc.
 */
@SuppressWarnings({ "unchecked" })
public void startElement(String uri, String localNameX, String qName, Attributes attrs) throws SAXException {
    if ("Query".equalsIgnoreCase(qName)) {
        queryName = attrs.getValue("name");
        rootElementName = queryName;
    } else if ("Class".equalsIgnoreCase(qName)) {
        processCriteria(attrs);
    } else if ("Union".equalsIgnoreCase(qName)) {
        inDetached = true;
        DetachedCriteria dc = DetachedCriteria.forEntityName(className);
        criteriaStack.push(dc);
    } else if ("NamedQuery".equalsIgnoreCase(qName)) {
        isNamedQuery = true;
        namedQuery = attrs.getValue("name");
        rootElementName = namedQuery;
        try {
            query = session.getNamedQuery(namedQuery);
        } catch (HibernateException he) {
            throw new SAXException("Failed to retrieve named query[" + namedQuery + "]", he);
        }
    } else if ("qparam".equalsIgnoreCase(qName)) {
        processQueryBind(attrs);
    } else if ("Join".equalsIgnoreCase(qName)) {
        processCriteria(attrs);
    } else if ("Projections".equalsIgnoreCase(qName)) {
        startProjection(attrs);
    } else if ("Projection".equalsIgnoreCase(qName)) {
        addProjection(attrs);
    } else if ("Order".equalsIgnoreCase(qName)) {
        if (isRowCountOnly() == false) {
            try {
                String name = attrs.getValue("name");
                String type = attrs.getValue("type");
                ((Criteria) criteriaStack.peek())
                        .addOrder(type.equalsIgnoreCase("asc") ? Order.asc(name) : Order.desc(name));
            } catch (Exception e) {
                throw new SAXException("Unable To Parse GreaterThan:" + attrs.getValue("name"), e);
            }
        }
    } else if ("GreaterThan".equalsIgnoreCase(qName)) {
        try {
            Operator operator = new Operator(attrs);
            addCriterion(Restrictions.gt(operator.getName(), operator.getNativeValue()));
        } catch (Exception e) {
            throw new SAXException("Unable To Parse GreaterThan:" + attrs.getValue("name"), e);
        }
    } else if ("GreaterThanOrEqual".equalsIgnoreCase(qName)) {
        try {
            Operator operator = new Operator(attrs);
            addCriterion(Restrictions.ge(operator.getName(), operator.getNativeValue()));
        } catch (Exception e) {
            throw new SAXException("Unable To Parse GreaterThanOrEqual:" + attrs.getValue("name"), e);
        }
    } else if ("LessThan".equalsIgnoreCase(qName)) {
        try {
            Operator operator = new Operator(attrs);
            addCriterion(Restrictions.lt(operator.getName(), operator.getNativeValue()));
        } catch (Exception e) {
            throw new SAXException("Unable To Parse LessThan:" + attrs.getValue("name"), e);
        }
    } else if ("LessThanOrEqual".equalsIgnoreCase(qName)) {
        try {
            Operator operator = new Operator(attrs);
            addCriterion(Restrictions.le(operator.getName(), operator.getNativeValue()));
        } catch (Exception e) {
            throw new SAXException("Unable To Parse LessThanOrEqual:" + attrs.getValue("name"), e);
        }
    } else if ("Equals".equalsIgnoreCase(qName)) {
        try {
            Operator operator = new Operator(attrs);
            if ("true".equalsIgnoreCase(attrs.getValue("not"))) {
                addCriterion(Restrictions.not(Restrictions.eq(operator.getName(), operator.getNativeValue())));
            } else {
                addCriterion(Restrictions.eq(operator.getName(), operator.getNativeValue()));
            }

        } catch (Exception e) {
            throw new SAXException("Unable To Parse Equals:" + attrs.getValue("name"), e);
        }
    } else if ("Alias".equalsIgnoreCase(qName)) {
        try {
            Operator operator = new Operator(attrs);
            ((Criteria) criteriaStack.peek()).createAlias(operator.getName(), operator.getValue());
        } catch (Exception e) {
            throw new SAXException("Unable To Create Alias:" + attrs.getValue("name"), e);
        }
    } else if ("GreaterThanProperty".equalsIgnoreCase(qName)) {
        try {
            Operator operator = new Operator(attrs);
            addCriterion(Restrictions.gtProperty(operator.getName(), operator.getName2()));
        } catch (Exception e) {
            throw new SAXException("Unable To Parse GreaterThanProperty:" + attrs.getValue("name"), e);
        }
    } else if ("GreaterThanOrEqualProperty".equalsIgnoreCase(qName)) {
        try {
            Operator operator = new Operator(attrs);
            addCriterion(Restrictions.geProperty(operator.getName(), operator.getName2()));
        } catch (Exception e) {
            throw new SAXException("Unable To Parse GreaterThanOrEqualProperty:" + attrs.getValue("name"), e);
        }
    } else if ("LessThanProperty".equalsIgnoreCase(qName)) {
        try {
            Operator operator = new Operator(attrs);
            addCriterion(Restrictions.ltProperty(operator.getName(), operator.getName2()));
        } catch (Exception e) {
            throw new SAXException("Unable To Parse LessThanProperty:" + attrs.getValue("name"), e);
        }
    } else if ("LessThanOrEqualProperty".equalsIgnoreCase(qName)) {
        try {
            Operator operator = new Operator(attrs);
            addCriterion(Restrictions.leProperty(operator.getName(), operator.getName2()));
        } catch (Exception e) {
            throw new SAXException("Unable To Parse LessThanOrEqualProperty:" + attrs.getValue("name"), e);
        }
    } else if ("EqualsProperty".equalsIgnoreCase(qName)) {
        try {
            Operator operator = new Operator(attrs);
            if ("true".equalsIgnoreCase(attrs.getValue("not"))) {
                addCriterion(
                        Restrictions.not(Restrictions.eqProperty(operator.getName(), operator.getName2())));
            } else {
                addCriterion(Restrictions.eqProperty(operator.getName(), operator.getName2()));
            }
        } catch (Exception e) {
            throw new SAXException("Unable To Parse EqualsProperty:" + attrs.getValue("name"), e);
        }
    } else if ("Like".equalsIgnoreCase(qName)) {
        try {
            Operator operator = new Operator(attrs);
            addCriterion(Restrictions.like(operator.getName(), operator.getNativeValue()));
        } catch (Exception e) {
            throw new SAXException("Unable To Parse Like:" + attrs.getValue("name"), e);
        }
    } else if ("Between".equalsIgnoreCase(qName)) {
        try {
            Operator operator = new Operator(attrs);
            addCriterion(Restrictions.between(operator.getName(), operator.getNativeValue(),
                    operator.getNativeValue2()));
        } catch (Exception e) {
            throw new SAXException("Unable To Parse Between:" + attrs.getValue("name"), e);
        }
    } else if ("IsEmpty".equalsIgnoreCase(qName)) {
        try {
            Operator operator = new Operator(attrs);
            addCriterion(Restrictions.isEmpty(operator.getName()));
        } catch (Exception e) {
            throw new SAXException("Unable To Parse IsEmpty:" + attrs.getValue("name"), e);
        }
    } else if ("IsNotEmpty".equalsIgnoreCase(qName)) {
        try {
            Operator operator = new Operator(attrs);
            addCriterion(Restrictions.isNotEmpty(operator.getName()));
        } catch (Exception e) {
            throw new SAXException("Unable To Parse IsNotEmpty:" + attrs.getValue("name"), e);
        }
    } else if ("IsNull".equalsIgnoreCase(qName)) {
        try {
            Operator operator = new Operator(attrs);
            addCriterion(Restrictions.isNull(operator.getName()));
        } catch (Exception e) {
            throw new SAXException("Unable To Parse IsNull:" + attrs.getValue("name"), e);
        }
    } else if ("IsNotNull".equalsIgnoreCase(qName)) {
        try {
            Operator operator = new Operator(attrs);
            addCriterion(Restrictions.isNotNull(operator.getName()));
        } catch (Exception e) {
            throw new SAXException("Unable To Parse IsNotNull:" + attrs.getValue("name"), e);
        }
    } else if ("In".equalsIgnoreCase(qName)) {
        try {
            Operator operator = new Operator(attrs);
            if (operator.isLiteral()) {
                addCriterion(new LiteralInExpression(operator.getName(), (String) operator.getNativeValue()));
            } else {
                addCriterion(Restrictions.in(operator.getName(), (Collection) operator.getNativeValue()));
            }
        } catch (Exception e) {
            throw new SAXException("Unable To Parse In:" + attrs.getValue("name"), e);
        }
    } else if ("SizeEquals".equalsIgnoreCase(qName)) {
        try {
            Operator operator = new Operator(attrs);
            int i = ((Integer) operator.getNativeValue()).intValue();
            addCriterion(Restrictions.sizeEq(operator.getName(), i));
        } catch (Exception e) {
            throw new SAXException("Unable To Parse SizeEquals:" + attrs.getValue("name"), e);
        }
    } else if ("Not".equalsIgnoreCase(qName)) {
        notStack.push(new Object());
    } else if ("Or".equalsIgnoreCase(qName)) {
        opStack.push(Restrictions.disjunction());
    } else if ("And".equalsIgnoreCase(qName)) {
        opStack.push(Restrictions.conjunction());
    } else {
        throw new SAXException("Element Name[" + qName + "] Not Recognized.");
    }
}

From source file:com.heliosapm.aa4h.parser.XMLQueryParser.java

License:Apache License

/**
 * Adds a criterion to the current item on the opStack.
 * If there are no items on the opStack, the criterion is added to the master criteria.
 * If the master criteria is added to, the notStack is checked to see if the added criterion should be negated.
 * @param criterion//from w  ww  . j  a v  a2  s.  co m
 */
protected void addCriterion(Criterion criterion) {
    if (opStack.size() > 0) {
        try {
            Object peekedObject = opStack.peek();
            peekedObject.getClass().getMethod("add", ADD_ARGS_TYPE).invoke(peekedObject,
                    new Object[] { criterion });
        } catch (Exception e) {
            log.error("XMLQueryBuilder addCriterion Method Failed", e);
            throw new RuntimeException("XMLQueryBuilder addCriterion Method Failed", e);
        }
    } else {
        if (notStack.size() > 0) {
            if (inDetached) {
                ((DetachedCriteria) criteriaStack.peek()).add(Restrictions.not(criterion));
            } else {
                ((Criteria) criteriaStack.peek()).add(Restrictions.not(criterion));
            }
        } else {
            if (inDetached) {
                ((DetachedCriteria) criteriaStack.peek()).add(criterion);
            } else {
                ((Criteria) criteriaStack.peek()).add(criterion);
            }
        }
    }
}

From source file:com.hmsinc.epicenter.model.surveillance.impl.SurveillanceRepositoryImpl.java

License:Open Source License

/**
 * @param c//from  w w w . j  ava2s .  c o m
 * @param startDate
 * @param endDate
 * @param includeAll
 * @param includeFacilityLocation
 * @param filter
 * @return
 */
private Criteria applyAnomalyCriteria(final Criteria c, final DateTime startDate, final DateTime endDate,
        final boolean includeAll, final Geometry filter, final Geometry excludeFacilityEventsFilter) {

    if (startDate == null && endDate != null) {
        c.add(Restrictions.lt("analysisTimestamp", endDate));
    } else if (startDate != null && endDate == null) {
        c.add(Restrictions.gt("analysisTimestamp", startDate));
    } else if (startDate != null && endDate != null) {
        c.add(Restrictions.between("analysisTimestamp", startDate, endDate));
    }

    if (!includeAll) {
        c.add(Restrictions.isEmpty("investigations")).createCriteria("disposition")
                .add(Restrictions.eq("type", WorkflowStateType.INITIAL));
    }

    if (filter != null && excludeFacilityEventsFilter == null) {

        c.createCriteria("geography").add(SpatialRestrictions.withinOrFilter("geometry", filter, 1000, true));

    } else if (filter == null && excludeFacilityEventsFilter != null) {

        final Conjunction conjunction = Restrictions.conjunction();
        c.createAlias("geography", "eventGeography");
        c.createAlias("task", "eventTask");

        conjunction.add(Restrictions.eq("eventTask.location", AnalysisLocation.FACILITY));
        conjunction.add(SpatialRestrictions.withinOrFilter("eventGeography.geometry",
                excludeFacilityEventsFilter, 1000, true));

        c.add(Restrictions.not(conjunction));

    } else if (filter != null && excludeFacilityEventsFilter != null) {

        final Conjunction conjunction = Restrictions.conjunction();
        c.createAlias("geography", "eventGeography");
        c.createAlias("task", "eventTask");

        // Find events where we have unlimited access
        conjunction.add(SpatialRestrictions.withinOrFilter("eventGeography.geometry", filter, 1000, true));

        // Filter events in the limited region
        final Conjunction facilityEventsConjunction = Restrictions.conjunction();
        facilityEventsConjunction.add(Restrictions.eq("eventTask.location", AnalysisLocation.FACILITY));
        facilityEventsConjunction.add(SpatialRestrictions.withinOrFilter("eventGeography.geometry",
                excludeFacilityEventsFilter, 1000, true));

        conjunction.add(Restrictions.not(facilityEventsConjunction));

        c.add(conjunction);
    }

    return c;
}

From source file:com.hypersocket.resource.AbstractAssignableResourceRepositoryImpl.java

License:Open Source License

@Override
public Long getAssignedResourceCount(List<Principal> principals, final String searchPattern,
        CriteriaConfiguration... configs) {

    Criteria criteria = createCriteria(getResourceClass());
    criteria.setProjection(Projections.property("id"));
    criteria.setResultTransformer(CriteriaSpecification.PROJECTION);
    if (StringUtils.isNotBlank(searchPattern)) {
        criteria.add(Restrictions.ilike("name", searchPattern));
    }//from  ww  w .j  a v  a 2 s .  c o  m

    for (CriteriaConfiguration c : configs) {
        c.configure(criteria);
    }

    criteria.add(Restrictions.eq("realm", principals.get(0).getRealm()));
    criteria = criteria.createCriteria("roles");
    criteria.add(Restrictions.eq("allUsers", true));

    List<?> ids = criteria.list();

    criteria = createCriteria(getResourceClass());
    criteria.setProjection(Projections.countDistinct("name"));
    criteria.setResultTransformer(CriteriaSpecification.PROJECTION);
    if (StringUtils.isNotBlank(searchPattern)) {
        criteria.add(Restrictions.ilike("name", searchPattern));
    }

    for (CriteriaConfiguration c : configs) {
        c.configure(criteria);
    }

    criteria.add(Restrictions.eq("realm", principals.get(0).getRealm()));
    if (ids.size() > 0) {
        criteria.add(Restrictions.not(Restrictions.in("id", ids)));
    }

    criteria = criteria.createCriteria("roles");
    criteria.add(Restrictions.eq("allUsers", false));
    criteria = criteria.createCriteria("principals");
    List<Long> pids = new ArrayList<Long>();
    for (Principal p : principals) {
        pids.add(p.getId());
    }
    criteria.add(Restrictions.in("id", pids));

    Long count = (Long) criteria.uniqueResult();
    return count + ids.size();

}

From source file:com.ihsolution.hqipo.dao.utils.QueryHelper.java

License:Open Source License

/**
 * Main conversion method/*from w w  w  .  ja  v a 2 s .  c  om*/
 * @param fieldName
 * @param fieldVal
 * @param oper (=, equal, IN ...)
 * @param j (AND OR)
 * @return
 */
public QueryHelper addFieldAndVal(String fieldName, Object fieldVal, String oper, Junction j) {

    boolean isValString = fieldVal instanceof String;
    String str = "";
    if (oper == null || "".equals(oper)) {
        oper = "equal";
    }

    if (isValString)
        str = ((String) fieldVal).trim();
    if ("equal".equals(oper)) {
        if (isValString) {
            j.add(Restrictions.eq(fieldName, str).ignoreCase());
        } else
            j.add(Restrictions.eq(fieldName, fieldVal));
    } else if ("notEqual".equals(oper)) {
        if (isValString) {
            j.add(Restrictions.ne(fieldName, str).ignoreCase());
        } else
            j.add(Restrictions.ne(fieldName, fieldVal));
    } else if ("null".equals(oper)) {
        j.add(Restrictions.isNull(fieldName));
    } else if ("notNull".equals(oper)) {
        j.add(Restrictions.isNotNull(fieldName));
    } else if ("notExists".equals(oper)) {
        j.add(Restrictions.sqlRestriction(fieldVal.toString()));
    } else if ("Exists".equals(oper)) {
        j.add(Restrictions.sqlRestriction(fieldVal.toString()));
    } else if (isValString) {
        MatchMode mm = getMatchMode(oper);
        if (mm != null)
            j.add(Restrictions.ilike(fieldName, str, mm));
    } else if ("le".equals(oper))
        j.add(Restrictions.le(fieldName, fieldVal));

    else if ("ge".equals(oper))
        j.add(Restrictions.ge(fieldName, fieldVal));
    else if ("gtProperty".equals(oper)) {
        String[] spl = ((String) fieldVal).split(";");
        if (spl.length == 2)
            j.add(Restrictions.gtProperty(spl[0], spl[1]));
        else
            j.add(Restrictions.gt(fieldName, fieldVal));
    } else if ("in".equals(oper)) {
        if (fieldVal instanceof Collection)
            j.add(Restrictions.in(fieldName, (Collection) fieldVal));
        else if (fieldVal instanceof Object[])
            j.add(Restrictions.in(fieldName, (Object[]) fieldVal));
        else
            throw new IllegalArgumentException(
                    "QueryHelper.IN illegal argument type. Should be Collection or Object[]");
    } else if ("notIn".equals(oper)) {
        if (fieldVal instanceof Collection)
            j.add(Restrictions.not(Restrictions.in(fieldName, (Collection) fieldVal)));
        else if (fieldVal instanceof Object[])
            j.add(Restrictions.not(Restrictions.in(fieldName, (Object[]) fieldVal)));
        else
            throw new IllegalArgumentException(
                    "QueryHelper.NOTIN illegal argument type. Should be Collection or Object[]");

    } else if ("between".equals(oper)) {
        Collection objs = (Collection) fieldVal;
        Iterator it2 = objs.iterator();
        Object obj1 = it2.next();
        Object obj2 = it2.next();

        j.add(Restrictions.between(fieldName, obj1 instanceof String ? obj1.toString().toLowerCase() : obj1,
                obj2 instanceof String ? obj2.toString().toLowerCase() : obj2));
    } else
        j.add(Restrictions.eq(fieldName, fieldVal));

    return this;
}