Example usage for org.hibernate.criterion Restrictions and

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

Introduction

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

Prototype

public static LogicalExpression and(Criterion lhs, Criterion rhs) 

Source Link

Document

Return the conjuction of two expressions

Usage

From source file:onl.netfishers.netshot.RestService.java

License:Open Source License

/**
 * Search tasks./* w ww. jav a2s. co m*/
 *
 * @param request the request
 * @param criteria the criteria
 * @return the list
 * @throws WebApplicationException the web application exception
 */
@POST
@Path("tasks/search")
@RolesAllowed("readonly")
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public List<Task> searchTasks(RsTaskCriteria criteria) throws WebApplicationException {

    logger.debug("REST request, search for tasks.");

    Session session = Database.getSession();
    try {
        Criteria c = session.createCriteria(Task.class);
        Task.Status status = null;
        try {
            if (!"ANY".equals(criteria.getStatus())) {
                status = Task.Status.valueOf(criteria.getStatus());
                c.add(Property.forName("status").eq(status));
            }
        } catch (Exception e) {
            logger.warn("Invalid status {}.", criteria.getStatus());
        }
        Calendar min = Calendar.getInstance();
        min.setTime(criteria.getDay());
        min.set(Calendar.HOUR_OF_DAY, 0);
        min.set(Calendar.MINUTE, 0);
        min.set(Calendar.SECOND, 0);
        min.set(Calendar.MILLISECOND, 0);
        Calendar max = (Calendar) min.clone();
        max.add(Calendar.DAY_OF_MONTH, 1);

        if (status == Task.Status.SUCCESS || status == Task.Status.FAILURE) {
            c.add(Property.forName("executionDate").between(min.getTime(), max.getTime()));
        } else if (status == Task.Status.CANCELLED) {
            c.add(Property.forName("changeDate").between(min.getTime(), max.getTime()));
        } else if (status == null) {
            c.add(Restrictions.or(Property.forName("status").eq(Task.Status.RUNNING),
                    Property.forName("status").eq(Task.Status.SCHEDULED),
                    Property.forName("executionDate").between(min.getTime(), max.getTime()),
                    Restrictions.and(Property.forName("executionDate").isNull(),
                            Property.forName("changeDate").between(min.getTime(), max.getTime()))));
        }
        c.addOrder(Property.forName("id").desc());

        @SuppressWarnings("unchecked")
        List<Task> tasks = c.list();
        return tasks;
    } catch (HibernateException e) {
        logger.error("Error while searching for tasks.", e);
        throw new NetshotBadRequestException("Unable to fetch the tasks",
                NetshotBadRequestException.NETSHOT_DATABASE_ACCESS_ERROR);
    } finally {
        session.close();
    }
}

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)
 *//*from   w  w  w .j a v a  2  s. c om*/
@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

/**
 * // w  ww . j av  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.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);//from w ww  .ja  va  2  s.co m
    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.auth.permissions.CheckJobStatusPermission.java

License:Open Source License

@Override
@SuppressWarnings("checkstyle:indentation")
public Criterion getCriteriaRestrictions(Class entityClass) {
    if (!entityClass.equals(JobStatus.class)) {
        return null;
    }//  w w  w.  j  av a 2  s  . c  om

    Conjunction conjunction = Restrictions.conjunction();
    // Org has to match.
    conjunction.add(Restrictions.in("ownerId", allowedOrgKeys));

    conjunction.add(Restrictions.or(Restrictions.ne("targetType", JobStatus.TargetType.OWNER),
            Restrictions.and(Restrictions.eq("targetType", JobStatus.TargetType.OWNER),
                    Restrictions.eqProperty("ownerId", "targetId"))));

    // If the principal is not a user, make sure to enforce a principalName match.
    if (!"user".equalsIgnoreCase(principalType)) {
        conjunction.add(Restrictions.eq("principalName", principalName));
    }
    return conjunction;
}

From source file:org.candlepin.auth.permissions.JobStatusPermission.java

License:Open Source License

@Override
@SuppressWarnings("checkstyle:indentation")
public Criterion getCriteriaRestrictions(Class entityClass) {
    if (!entityClass.equals(JobStatus.class)) {
        return null;
    }/*from w w  w .j a  va  2s .co m*/

    Conjunction conjunction = Restrictions.conjunction();
    // Org has to match.
    conjunction.add(Restrictions.in("ownerId", allowedOrgIds));

    conjunction.add(Restrictions.or(Restrictions.ne("targetType", JobStatus.TargetType.OWNER),
            Restrictions.and(Restrictions.eq("targetType", JobStatus.TargetType.OWNER),
                    Restrictions.eqProperty("ownerId", "targetId"))));

    // If the principal is not a user, make sure to enforce a principalName match.
    if (!"user".equalsIgnoreCase(principalType)) {
        conjunction.add(Restrictions.eq("principalName", principalName));
    }
    return conjunction;
}

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//from  www . j  av  a 2s .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.model.EntitlementCurator.java

License:Open Source License

private Criteria createModifiesDateFilteringCriteria(Consumer consumer, Date startDate, Date endDate) {
    Criteria criteria = currentSession().createCriteria(Entitlement.class)
            .add(Restrictions.eq("consumer", consumer)).createCriteria("pool").add(Restrictions.or(
                    // Dates overlap if the start or end date is in our range
                    Restrictions.or(Restrictions.between("startDate", startDate, endDate),
                            Restrictions.between("endDate", startDate, endDate)),
                    Restrictions.and(
                            // The dates overlap if our range is completely encapsulated
                            Restrictions.le("startDate", startDate), Restrictions.ge("endDate", endDate))));
    return criteria;
}

From source file:org.candlepin.model.PoolCurator.java

License:Open Source License

/**
 * @param consumer//from  w w  w .ja va  2s. c o  m
 * @param stackId
 * @return Number of derived pools which exist for the given consumer and stack
 */
public Pool getSubPoolForStackId(Consumer consumer, String stackId) {
    Criteria getCount = createSecureCriteria().createAlias("sourceStack", "ss")
            .add(Restrictions.eq("ss.sourceConsumer", consumer)).add(Restrictions.and(
                    Restrictions.isNotNull("ss.sourceStackId"), Restrictions.eq("ss.sourceStackId", stackId)));
    return (Pool) getCount.uniqueResult();
}