Example usage for org.hibernate.criterion Restrictions gt

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

Introduction

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

Prototype

public static SimpleExpression gt(String propertyName, Object value) 

Source Link

Document

Apply a "greater than" constraint to the named property

Usage

From source file:org.apache.usergrid.apm.service.charts.filter.DateIntervalFilter.java

License:Apache License

/** 
 * Prepare criteria according to filter values. Ideally when both from and to are present, it should result into two criterion
 * startTime >= from and endTime <= to but given that delta between startTime and endTime is not huge and we don't have to be 
 * precise upto few minutes, selecting startTime between from and to should work. It should also help with faster query as well.
 * @return/*from  w  w  w  . j a va2 s .  c  o m*/
 */
public Criterion getCriteria() {

    if (getFilterEmpty())
        return null;

    if (from != null && to != null)
        return Restrictions.between(startTime, from, to);

    Criterion crit = null;
    if (from != null)
        crit = Restrictions.gt(startTime, from);
    else
        crit = Restrictions.lt(endTime, to);

    return crit;
}

From source file:org.apache.usergrid.apm.service.charts.filter.EndPeriodFilter.java

License:Apache License

@Override
public Criterion getCriteria() {

    if (getFilterEmpty())
        return null;
    //see http://stackoverflow.com/questions/84644/hibernate-query-by-example-and-projections on why this. is needed
    //log.info("Time Range Filter Criteria between " + from + " & " + to);

    return Restrictions.and(Restrictions.gt("this." + propertyName, from),
            Restrictions.le("this." + propertyName, to));

    //return Restrictions.between("this."+propertyName, from, to);    
}

From source file:org.apache.usergrid.apm.service.charts.filter.SpecialTimeFilter.java

License:Apache License

/**
 * Active session for a time range is one with (start <= endTime AND end > startTime)
 */// ww  w  .ja  v  a 2 s  .c o m
@Override
public Criterion getCriteria() {
    if (getFilterEmpty())
        return null;
    //see http://stackoverflow.com/questions/84644/hibernate-query-by-example-and-projections on why this. is needed

    return Restrictions.and(Restrictions.le("this." + startPropName, to),
            Restrictions.gt("this." + endPropName, from));

}

From source file:org.apache.usergrid.apm.service.charts.filter.TimeRangeFilter.java

License:Apache License

/**
 * /*ww w  .  j a  v  a 2  s .  c  o m*/
 * @param lastx 
 * 
 *//*
    public TimeRangeFilter (ChartCriteria.LastX lastx) {
            
    Calendar start = Calendar.getInstance();
    Calendar end = Calendar.getInstance();
            
    switch (lastx)  {
    case LAST_HOUR:
     propertyName = "endMinute";
     start.add(Calendar.MINUTE, -60); 
     from = start.getTimeInMillis()/1000/60;         
     to = end.getTimeInMillis()/1000/60;
     break;
    case LAST_DAY:
     propertyName = "endHour";
     start.add(Calendar.DATE, -1);
     from = start.getTimeInMillis()/1000/60/60;
     to = end.getTimeInMillis()/1000/60/60;
     break;
    case LAST_WEEK:
     propertyName = "endDay";
     start.add(Calendar.DATE, -7);
     from = start.getTimeInMillis()/1000/60/60/24;
     to = end.getTimeInMillis()/1000/60/60/24;
     break;
    case LAST_MONTH:
     propertyName = "endDay";
     start.add(Calendar.MONTH, -1);
     from = start.getTimeInMillis()/1000/60/60/24;
     to = end.getTimeInMillis()/1000/60/60/24;
     break;
    case LAST_YEAR:
     propertyName = "endMonth";
     start.add(Calendar.YEAR, -1);
     from = start.getTimeInMillis()/1000/60/60/24/30; //Approximately
     to = end.getTimeInMillis()/1000/60/60/24/30;
     break;      
    }
            
    }
            
            
    public TimeRangeFilter( ChartCriteria.SamplePeriod sp, Date start, Date end)  {
    switch (sp)  {
    case MINUTE:
     propertyName = "endMinute";
     from = start.getTime()/1000/60;         
     to = end.getTime()/1000/60;
     break;
    case HOUR:
     propertyName = "endHour";
     from = start.getTime()/1000/60/60;
     to = end.getTime()/1000/60/60;
     break;
    case DAY:
     propertyName = "endDay";
     from = start.getTime()/1000/60/60/24;
     to =   end.getTime()/1000/60/60/24;
     break;
    case WEEK:
     propertyName = "endWeek";
     from = start.getTime()/1000/60/60/24/7;
     to =   end.getTime()/1000/60/60/24/7;
     break;
    case MONTH:
     propertyName = "endMonth";
     from = start.getTime()/1000/60/60/24/30; //Approximately
     to = end.getTime()/1000/60/60/24/30;
     break;      
    }
            
    }
    */
@Override
public Criterion getCriteria() {

    if (getFilterEmpty())
        return null;
    //see http://stackoverflow.com/questions/84644/hibernate-query-by-example-and-projections on why this. is needed
    //log.info("Time Range Filter Criteria between " + from + " & " + to);

    return Restrictions.and(Restrictions.gt("this." + propertyName, from),
            Restrictions.le("this." + propertyName, to));

    //return Restrictions.between("this."+propertyName, from, to);      
}

From source file:org.apache.usergrid.apm.service.SessionDBServiceImpl.java

License:Apache License

@SuppressWarnings("unchecked")
public List<String> getDistinctValuesFromSummarySessionMetrics(String column, Date since)
        throws HibernateException {
    //String query = "SELECT DISTINCT " + column + "FROM SUMMARY_SESSION_METRICS where " +
    log.info("Getting distinct values for " + column + " since " + since);
    List<String> results = null;
    Session session = null;/*from   w  ww. j  a v a  2s . c  o  m*/
    Transaction transaction = null;
    try {
        session = ServiceFactory.getAnalyticsHibernateSession();
        transaction = session.beginTransaction();
        Criteria crit = session.createCriteria(SummarySessionMetrics.class);
        crit.add(Restrictions.gt("sessionEndTime", since));
        crit.setProjection(Projections.distinct(Projections.property(column)));
        results = (List<String>) crit.list();
        transaction.commit();
    } catch (Exception e) {
        e.printStackTrace();
        transaction.rollback();
        throw new HibernateException("Cannot get distict values from SummarySessionMetrics ", e);
    }
    return results;

}

From source file:org.balisunrise.daa.hibernate.HCriteria.java

License:Open Source License

private org.hibernate.criterion.Criterion makeCriterion(String propertyName, FilterType type, Object value,
        Object otherValue) {/*from   w  w  w  .  jav a 2s  . c om*/

    switch (type) {
    case EQUALS:
        return Restrictions.eq(propertyName, value);
    case EQUALS_OR_NULL:
        return Restrictions.eqOrIsNull(propertyName, value);
    case DIFFERENT:
        return Restrictions.ne(propertyName, value);
    case DIFFERENT_OR_NOT_NULL:
        return Restrictions.neOrIsNotNull(propertyName, value);
    case GREATHER:
        return Restrictions.gt(propertyName, value);
    case GREATHER_EQUALS:
        return Restrictions.ge(propertyName, value);
    case LESS:
        return Restrictions.lt(propertyName, value);
    case LESS_EQUALS:
        return Restrictions.le(propertyName, value);
    case LIKE:
        return Restrictions.like(propertyName, value + "%");
    case ILIKE:
        return Restrictions.ilike(propertyName, "%" + value + "%");
    case BETWEEN:
        return Restrictions.between(propertyName, value, otherValue);
    case IN:
        if (value instanceof Collection)
            return Restrictions.in(propertyName, (Collection) value);
        else if (value instanceof Object[])
            return Restrictions.in(propertyName, (Object[]) value);
        else
            return Restrictions.in(propertyName, new Object[] { value });
    case NULL:
        return Restrictions.isNull(propertyName);
    case NOT_NULL:
        return Restrictions.isNotNull(propertyName);
    default:
        return null;
    }
}

From source file:org.brekka.pegasus.core.dao.hibernate.TemplateHibernateDAO.java

License:Apache License

@SuppressWarnings("unchecked")
@Override/*from w ww  .j ava  2s . c o m*/
public List<Template> retrieveListing(final DateTime changedSince, final ListingCriteria listingCriteria) {
    Criteria criteria = getCurrentSession().createCriteria(Template.class);
    if (changedSince != null) {
        Criteria xmlEntityCriteria = criteria.createCriteria("xml");
        xmlEntityCriteria.add(Restrictions.gt("created", changedSince.toDate()));
    }
    HibernateUtils.applyCriteria(criteria, listingCriteria);
    return criteria.list();
}

From source file:org.broadleafcommerce.core.offer.dao.OfferDaoImpl.java

License:Apache License

@Override
public List<Offer> readOffersByAutomaticDeliveryType() {
    //TODO change this to a JPA criteria
    Criteria criteria = ((HibernateEntityManager) em).getSession().createCriteria(OfferImpl.class);

    Date myDate = getCurrentDateAfterFactoringInDateResolution();

    Calendar c = Calendar.getInstance();
    c.setTime(myDate);/*w w  w.  j  av  a  2s . com*/
    c.add(Calendar.DATE, +1);
    criteria.add(Restrictions.lt("startDate", c.getTime()));
    c = Calendar.getInstance();
    c.setTime(myDate);
    c.add(Calendar.DATE, -1);
    criteria.add(Restrictions.or(Restrictions.isNull("endDate"), Restrictions.gt("endDate", c.getTime())));
    criteria.add(Restrictions.or(Restrictions.eq("archiveStatus.archived", 'N'),
            Restrictions.isNull("archiveStatus.archived")));

    // Automatically Added or (Automatically Added is null and deliveryType is Automatic)
    criteria.add(Restrictions.or(Restrictions.eq("automaticallyAdded", true), Restrictions
            .and(Restrictions.isNull("automaticallyAdded"), Restrictions.eq("deliveryType", "AUTOMATIC"))));

    criteria.setCacheable(true);
    criteria.setCacheRegion("query.Offer");

    return criteria.list();
}

From source file:org.candlepin.gutterball.curator.ComplianceSnapshotCurator.java

License:Open Source License

/**
 * Retrieves an iterator over the compliance snapshots on the target date.
 *
 * @param targetDate//w ww  .j  a  va2s .c  o  m
 *  The date for which to retrieve compliance snapshots. If null, the current date will be used
 *  instead.
 *
 * @param consumerUuids
 *  A list of consumer UUIDs to use to filter the results. If provided, only compliances for
 *  consumers in the list will be retrieved.
 *
 * @param ownerFilters
 *  A list of owners to use to filter the results. If provided, only compliances for consumers
 *  belonging to the specified owners (orgs) will be retrieved.
 *
 * @param statusFilters
 *  A list of statuses to use to filter the results. If provided, only compliances with a status
 *  matching the list will be retrieved.
 *
 * @param productNameFilters
 *  A list of product names to use to filter compliances. If provided, only compliances for
 *  consumers having installed the specified products will be retrieved.
 *
 * @param subscriptionSkuFilters
 *  A list of subscription skus to use to filter compliances. If provided, only compliances for
 *  the specified subscription skus will be retrieved.
 *
 * @param subscriptionNameFilters
 *  A list of subscription names to use to filter compliances. If provided, only compliances for
 *  the specified subscription names will be retrieved.
 *
 * @param attributeFilters
 *  A map of entitlement attributes to use to filter compliances. If provided, only compliances
 *  for entitlements having the specified values for the given attributes will be retrieved.
 *
 * @param pageRequest
 *  A PageRequest instance containing paging information from the request. If null, no paging
 *  will be performed.
 *
 * @return
 *  A Page instance containing an iterator over the compliance snapshots for the target date and
 *  the paging information for the query.
 */
@SuppressWarnings("checkstyle:indentation")
public Page<Iterator<Compliance>> getSnapshotIterator(Date targetDate, List<String> consumerUuids,
        List<String> ownerFilters, List<String> statusFilters, List<String> productNameFilters,
        List<String> subscriptionSkuFilters, List<String> subscriptionNameFilters,
        Map<String, String> attributeFilters, PageRequest pageRequest) {

    Page<Iterator<Compliance>> page = new Page<Iterator<Compliance>>();
    page.setPageRequest(pageRequest);

    DetachedCriteria subquery = DetachedCriteria.forClass(Compliance.class);
    subquery.createAlias("consumer", "c");
    subquery.createAlias("c.consumerState", "state");

    // https://hibernate.atlassian.net/browse/HHH-2776
    if (consumerUuids != null && !consumerUuids.isEmpty()) {
        subquery.add(Restrictions.in("c.uuid", consumerUuids));
    }

    Date toCheck = targetDate == null ? new Date() : targetDate;
    subquery.add(
            Restrictions.or(Restrictions.isNull("state.deleted"), Restrictions.gt("state.deleted", toCheck)));
    subquery.add(Restrictions.le("state.created", toCheck));

    if (ownerFilters != null && !ownerFilters.isEmpty()) {
        subquery.createAlias("c.owner", "o");
        subquery.add(Restrictions.in("o.key", ownerFilters));
    }

    subquery.add(Restrictions.le("date", toCheck));

    subquery.setProjection(
            Projections.projectionList().add(Projections.max("date")).add(Projections.groupProperty("c.uuid")));

    Session session = this.currentSession();
    Criteria query = session.createCriteria(Compliance.class, "comp").createAlias("comp.consumer", "cs")
            .add(Subqueries.propertiesIn(new String[] { "comp.date", "cs.uuid" }, subquery))
            .setCacheMode(CacheMode.IGNORE).setReadOnly(true);

    if ((statusFilters != null && !statusFilters.isEmpty())
            || (attributeFilters != null && attributeFilters.containsKey("management_enabled"))
            || (productNameFilters != null && !productNameFilters.isEmpty())) {

        query.createAlias("comp.status", "stat");

        if (statusFilters != null && !statusFilters.isEmpty()) {
            query.add(Restrictions.in("stat.status", statusFilters));
        }

        if (attributeFilters != null && attributeFilters.containsKey("management_enabled")) {
            boolean managementEnabledFilter = PropertyConverter
                    .toBoolean(attributeFilters.get("management_enabled"));
            query.add(Restrictions.eq("stat.managementEnabled", managementEnabledFilter));
        }

        if (productNameFilters != null && !productNameFilters.isEmpty()) {
            query.createAlias("stat.compliantProducts", "cprod", JoinType.LEFT_OUTER_JOIN)
                    .createAlias("stat.partiallyCompliantProducts", "pcprod", JoinType.LEFT_OUTER_JOIN)
                    .createAlias("stat.nonCompliantProducts", "ncprod", JoinType.LEFT_OUTER_JOIN);

            DetachedCriteria prodQuery = DetachedCriteria.forClass(Compliance.class, "comp2");
            prodQuery.createAlias("comp2.consumer", "cons2");
            prodQuery.createAlias("cons2.installedProducts", "installed");
            prodQuery.add(Restrictions.and(Restrictions.in("installed.productName", productNameFilters),
                    Restrictions.eqProperty("comp2.id", "comp.id")));
            prodQuery.setProjection(Projections.property("installed.productId"));

            query.add(Restrictions.or(Property.forName("cprod.productId").in(prodQuery),
                    Property.forName("pcprod.productId").in(prodQuery),
                    Property.forName("ncprod.productId").in(prodQuery)));
        }
    }

    // Add subscription filters, if necessary
    if ((subscriptionSkuFilters != null && !subscriptionSkuFilters.isEmpty())
            || (subscriptionNameFilters != null && !subscriptionNameFilters.isEmpty())) {

        // Impl note: We have to be very careful with alias names, as Hibernate has a tendancy
        // to errorneously truncate "long" ones. Actual property/field names are safe, though.
        query.createAlias("comp.entitlements", "entsnap");

        if (subscriptionSkuFilters != null && !subscriptionSkuFilters.isEmpty()) {
            query.add(Restrictions.in("entsnap.productId", subscriptionSkuFilters));
        }

        if (subscriptionNameFilters != null && !subscriptionNameFilters.isEmpty()) {
            query.add(Restrictions.in("entsnap.productName", subscriptionNameFilters));
        }
    }

    if (pageRequest != null && pageRequest.isPaging()) {
        page.setMaxRecords(this.getRowCount(query));

        query.setFirstResult((pageRequest.getPage() - 1) * pageRequest.getPerPage());
        query.setMaxResults(pageRequest.getPerPage());

        if (pageRequest.getSortBy() != null) {
            query.addOrder(
                    pageRequest.getOrder() == PageRequest.Order.ASCENDING ? Order.asc(pageRequest.getSortBy())
                            : Order.desc(pageRequest.getSortBy()));
        }
    }

    page.setPageData(new AutoEvictingColumnarResultsIterator<Compliance>(session,
            query.scroll(ScrollMode.FORWARD_ONLY), 0));

    return page;
}

From source file:org.candlepin.gutterball.curator.ComplianceSnapshotCurator.java

License:Open Source License

/**
 * Retrieves an iterator over the compliance snapshots for the specified consumer.
 *
 * @param consumerUUID// ww  w  .j  a va2s  .  co  m
 *  The UUID for the consumer for which to retrieve compliance snapshots.
 *
 * @param startDate
 *  The start date to use to filter snapshots retrieved. If specified, only snapshots occurring
 *  after the start date, and the snapshot immediately preceding it, will be retrieved.
 *
 * @param endDate
 *  The end date to use to filter snapshots retrieved. If specified, only snapshots occurring
 *  before the end date will be retrieved.
 *
 * @param pageRequest
 *  A PageRequest instance containing paging information from the request. If null, no paging
 *  will be performed.
 *
 * @return
 *  A Page instance containing an iterator over the snapshots for the specified consumer, and
 *  the paging information for the query.
 */
@SuppressWarnings("checkstyle:indentation")
public Page<Iterator<Compliance>> getSnapshotIteratorForConsumer(String consumerUUID, Date startDate,
        Date endDate, PageRequest pageRequest) {

    Page<Iterator<Compliance>> page = new Page<Iterator<Compliance>>();
    page.setPageRequest(pageRequest);

    Session session = this.currentSession();
    Criteria query = session.createCriteria(Compliance.class, "comp1");
    query.createAlias("comp1.consumer", "cons1");

    query.add(Restrictions.eq("cons1.uuid", consumerUUID));

    if (startDate != null) {
        DetachedCriteria subquery = DetachedCriteria.forClass(Compliance.class, "comp2");
        subquery.createAlias("comp2.consumer", "cons2");
        subquery.createAlias("cons2.consumerState", "state2");

        subquery.add(Restrictions.or(Restrictions.isNull("state2.deleted"),
                Restrictions.gt("state2.deleted", startDate)));

        subquery.add(Restrictions.lt("state2.created", startDate));
        subquery.add(Restrictions.eqProperty("cons2.uuid", "cons1.uuid"));
        subquery.add(Restrictions.lt("comp2.date", startDate));

        subquery.setProjection(Projections.projectionList().add(Projections.max("comp2.date")));

        query.add(Restrictions.disjunction().add(Restrictions.ge("comp1.date", startDate))
                .add(Subqueries.propertyEq("comp1.date", subquery)));
    }

    if (endDate != null) {
        query.add(Restrictions.le("comp1.date", endDate));
    }

    query.setCacheMode(CacheMode.IGNORE);
    query.setReadOnly(true);

    if (pageRequest != null && pageRequest.isPaging()) {
        page.setMaxRecords(this.getRowCount(query));

        query.setFirstResult((pageRequest.getPage() - 1) * pageRequest.getPerPage());
        query.setMaxResults(pageRequest.getPerPage());

        if (pageRequest.getSortBy() != null) {
            query.addOrder(
                    pageRequest.getOrder() == PageRequest.Order.ASCENDING ? Order.asc(pageRequest.getSortBy())
                            : Order.desc(pageRequest.getSortBy()));
        }
    }

    page.setPageData(new AutoEvictingColumnarResultsIterator<Compliance>(session,
            query.scroll(ScrollMode.FORWARD_ONLY), 0));

    return page;
}