Example usage for org.hibernate.criterion Restrictions lt

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

Introduction

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

Prototype

public static SimpleExpression lt(String propertyName, Object value) 

Source Link

Document

Apply a "less than" constraint to the named property

Usage

From source file:moos.ssds.dao.DataProducerDAO.java

License:LGPL

/**
 * This method finds all the deployments of a <code>Device</code> that fall
 * within a certain time window. This is usually done when searching for
 * data from that device.//from  w  w w.j av a 2s .c  o  m
 * 
 * @param device
 * @param startDate
 * @param endDate
 * @param orderByPropertyName
 * @param ascendingOrDescending
 * @param returnFullObjectGraph
 * @return
 * @throws MetadataAccessException
 */
public Collection findByDeviceAndTimeWindow(Device device, Date startDate, Date endDate,
        String orderByPropertyName, String ascendingOrDescending, boolean returnFullObjectGraph)
        throws MetadataAccessException {

    // The collection to return
    Collection dataProducersToReturn = new ArrayList();

    // First make sure the device exists
    DeviceDAO deviceDAO = new DeviceDAO(getSession());

    Device persistentDevice = null;
    persistentDevice = (Device) deviceDAO.findEquivalentPersistentObject(device, false);

    if (persistentDevice == null)
        return dataProducersToReturn;

    // Create the criteria
    try {
        Criteria criteria = getSession().createCriteria(DataProducer.class);
        criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
        criteria.add(Restrictions.eq("device", persistentDevice));
        criteria.add(Restrictions.eq("dataProducerType", DataProducer.TYPE_DEPLOYMENT));
        // Add the time criteria
        if (startDate != null) {
            criteria.add(
                    Restrictions.or(Restrictions.gt("endDate", startDate), Restrictions.isNull("endDate")));
        }
        if (endDate != null) {
            criteria.add(
                    Restrictions.or(Restrictions.lt("startDate", endDate), Restrictions.isNull("startDate")));
        }
        addOrderByCriteria(criteria, orderByPropertyName, ascendingOrDescending);
        dataProducersToReturn = criteria.list();
    } catch (HibernateException e) {
        throw new MetadataAccessException(e.getMessage());
    }

    // If the full object graphs are requested
    if (returnFullObjectGraph)
        dataProducersToReturn = getRealObjectsAndRelationships(dataProducersToReturn);

    return dataProducersToReturn;
}

From source file:moos.ssds.dao.DataProducerDAO.java

License:LGPL

/**
 * TODO kgomes document this/*from  w ww.ja  v  a2  s . c  o m*/
 * 
 * @param countQuery
 * @param id
 * @param name
 * @param exactNameMatch
 * @param dataProducerType
 * @param startDate
 * @param boundedByStartDate
 * @param endDate
 * @param boundedByEndDate
 * @param geospatialLatMin
 * @param geospatialLatMax
 * @param geospatialLonMin
 * @param geospatialLonMax
 * @param geospatialDepthMin
 * @param geospatialDepthMax
 * @param geospatialBenthicAltitudeMin
 * @param geospatialBenthicAltitudeMax
 * @param hostName
 * @param exactHostNameMatch
 * @param orderByProperty
 * @param ascendOrDescend
 * @return
 * @throws MetadataAccessException
 */
private Criteria formulatePropertyCriteria(boolean countQuery, Long id, String name, boolean exactNameMatch,
        String dataProducerType, Date startDate, boolean boundedByStartDate, Date endDate,
        boolean boundedByEndDate, Double geospatialLatMin, Double geospatialLatMax, Double geospatialLonMin,
        Double geospatialLonMax, Float geospatialDepthMin, Float geospatialDepthMax,
        Float geospatialBenthicAltitudeMin, Float geospatialBenthicAltitudeMax, String hostName,
        boolean exactHostNameMatch, String orderByProperty, String ascendOrDescend)
        throws MetadataAccessException {
    // The Criteria to return
    Criteria criteria = getSession().createCriteria(DataProducer.class);
    // Make it distinct
    criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);

    // Check for exceptional conditions on the query
    if ((dataProducerType != null) && (!DataProducer.isValidDataProducerType(dataProducerType)))
        throw new MetadataAccessException("The dataProducerType (" + dataProducerType
                + ") does not match a constant defined in the DataProducer class");
    if ((geospatialLatMin != null) && (geospatialLatMax != null))
        if (geospatialLatMax.doubleValue() < geospatialLatMin.doubleValue())
            throw new MetadataAccessException("The maximum latitude specified was less than the minimum.");
    if ((geospatialLonMin != null) && (geospatialLonMax != null))
        if (geospatialLonMax.doubleValue() < geospatialLonMin.doubleValue())
            throw new MetadataAccessException("The maximum longitude specified was less than the minimum.");
    if ((geospatialDepthMin != null) && (geospatialDepthMax != null))
        if (geospatialDepthMax.doubleValue() < geospatialDepthMin.doubleValue())
            throw new MetadataAccessException("The depth maximum specified was less than the minimum.");
    if ((geospatialBenthicAltitudeMin != null) && (geospatialBenthicAltitudeMax != null))
        if (geospatialBenthicAltitudeMax.doubleValue() < geospatialBenthicAltitudeMin.doubleValue())
            throw new MetadataAccessException(
                    "The benthic altitude maximum specified was less than the minimum.");
    if ((startDate != null) && (endDate != null) && (endDate.before(startDate)))
        throw new MetadataAccessException("The end date specified (" + endDate
                + ") is before the start date specified (" + startDate + ")");

    // Now build the Criteria
    if (id != null) {
        criteria.add(Restrictions.eq("id", id));
    } else {
        if ((name != null) && (!name.equals(""))) {
            if (exactNameMatch) {
                criteria.add(Restrictions.eq("name", name));
            } else {
                criteria.add(Restrictions.like("name", "%" + name + "%"));
            }
        }
        if (dataProducerType != null) {
            criteria.add(Restrictions.eq("dataProducerType", dataProducerType));
        }
        if (startDate != null) {
            criteria.add(
                    Restrictions.or(Restrictions.gt("endDate", startDate), Restrictions.isNull("endDate")));
            if (boundedByStartDate) {
                criteria.add(Restrictions.gt("startDate", startDate));
            }
        }
        if (endDate != null) {
            criteria.add(
                    Restrictions.or(Restrictions.lt("startDate", endDate), Restrictions.isNull("startDate")));
            if (boundedByEndDate) {
                criteria.add(Restrictions.lt("endDate", endDate));
            }
        }
        if (geospatialLatMin != null)
            criteria.add(Restrictions.ge("nominalLatitude", geospatialLatMin));

        if (geospatialLatMax != null)
            criteria.add(Restrictions.le("nominalLatitude", geospatialLatMax));

        if (geospatialLonMin != null)
            criteria.add(Restrictions.ge("nominalLongitude", geospatialLonMin));

        if (geospatialLonMax != null)
            criteria.add(Restrictions.le("nominalLongitude", geospatialLonMax));

        if (geospatialDepthMin != null)
            criteria.add(Restrictions.le("nominalDepth", geospatialDepthMin));

        if (geospatialDepthMax != null)
            criteria.add(Restrictions.ge("nominalDepth", geospatialDepthMax));

        if (geospatialBenthicAltitudeMin != null)
            criteria.add(Restrictions.ge("benthicAltitude", geospatialBenthicAltitudeMin));

        if (geospatialBenthicAltitudeMax != null)
            criteria.add(Restrictions.lt("benthicAltitude", geospatialBenthicAltitudeMax));
        if ((hostName != null) && (!hostName.equals(""))) {
            if (exactHostNameMatch) {
                criteria.add(Restrictions.eq("hostName", hostName));
            } else {
                criteria.add(Restrictions.like("hostName", "%" + hostName + "%"));
            }
        }
    }
    // Setup if a count query, if not add fetching and ordering
    if (countQuery) {
        criteria.setProjection(Projections.rowCount());
    } else {
        addOrderByCriteria(criteria, orderByProperty, ascendOrDescend);
    }
    // Now return the Criteria
    return criteria;
}

From source file:moos.ssds.dao.EventDAO.java

License:LGPL

/**
 * TODO kgomes document this/*from   w  ww. ja  va 2s  .co m*/
 * 
 * @param name
 * @param startDate
 * @param endDate
 * @param returnFullObjectGraph
 * @return
 * @throws MetadataAccessException
 */
public Event findByNameAndDates(String name, Date startDate, Date endDate, boolean returnFullObjectGraph)
        throws MetadataAccessException {

    // The event to return
    Event eventToReturn = null;

    // First check to see if the parameters are OK
    if ((name == null) || (name.equals("")) || (startDate == null) || (endDate == null))
        return null;

    // Check to make sure they are in correct sequence
    if (endDate.before(startDate))
        throw new MetadataAccessException("End date specified is before the start date. "
                + "Now that just doesn't make sense now does it?");

    // Create of window around the start and end dates to effectively remove
    // the milliseconds from the query (which are unreliable in storing in
    // the DB)
    Date startDateRoundDown = DateUtils.roundDateDownToSeconds(startDate);
    Date startDateNextSecond = new Date(startDateRoundDown.getTime() + 1000);
    Date endDateRoundDown = DateUtils.roundDateDownToSeconds(endDate);
    Date endDateNextSecond = new Date(endDateRoundDown.getTime() + 1000);

    // Now build and perform the query
    eventToReturn = (Event) this.getSession().createCriteria(Event.class).add(Restrictions.eq("name", name))
            .add(Restrictions.lt("startDate", startDateNextSecond))
            .add(Restrictions.ge("startDate", startDateRoundDown))
            .add(Restrictions.lt("endDate", endDateNextSecond))
            .add(Restrictions.ge("endDate", endDateRoundDown)).uniqueResult();

    // Check for objectgraph
    if (returnFullObjectGraph)
        eventToReturn = (Event) getRealObjectAndRelationships(eventToReturn);

    // Return the result
    return eventToReturn;
}

From source file:moos.ssds.dao.EventDAO.java

License:LGPL

/**
 * //from   ww w. j a  va 2  s . c om
 * @param countQuery
 * @param id
 * @param name
 * @param exactNameMatch
 * @param startDate
 * @param boundedByStartDate
 * @param endDate
 * @param boundedByEndDate
 * @param orderByProperty
 * @param ascendOrDescend
 * @return
 * @throws MetadataAccessException
 */
private Criteria formulatePropertyCriteria(boolean countQuery, Long id, String name, boolean exactNameMatch,
        Date startDate, boolean boundedByStartDate, Date endDate, boolean boundedByEndDate,
        String orderByProperty, String ascendOrDescend) throws MetadataAccessException {

    // The Criteria to return
    Criteria criteria = getSession().createCriteria(Event.class);

    // Make it distinct
    criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);

    // Check for exceptional conditions on the query
    if ((startDate != null) && (endDate != null) && (endDate.before(startDate)))
        throw new MetadataAccessException("The end date specified (" + endDate
                + ") is before the start date specified (" + startDate + ")");

    // Now build the Criteria
    if (id != null) {
        criteria.add(Restrictions.eq("id", id));
    } else {
        if ((name != null) && (!name.equals(""))) {
            if (exactNameMatch) {
                criteria.add(Restrictions.eq("name", name));
            } else {
                criteria.add(Restrictions.like("name", "%" + name + "%"));
            }
        }
        if (startDate != null) {
            criteria.add(
                    Restrictions.or(Restrictions.gt("endDate", startDate), Restrictions.isNull("endDate")));
            if (boundedByStartDate) {
                criteria.add(Restrictions.gt("startDate", startDate));
            }
        }
        if (endDate != null) {
            criteria.add(
                    Restrictions.or(Restrictions.lt("startDate", endDate), Restrictions.isNull("startDate")));
            if (boundedByEndDate) {
                criteria.add(Restrictions.lt("endDate", endDate));
            }
        }
    }

    // Setup if a count query, if not add fetching and ordering
    if (countQuery) {
        criteria.setProjection(Projections.rowCount());
    } else {
        addOrderByCriteria(criteria, orderByProperty, ascendOrDescend);
    }

    // Now return the Criteria
    return criteria;
}

From source file:net.databinder.models.hib.CriteriaFilterAndSort.java

License:Open Source License

public void buildUnordered(Criteria criteria) {
    super.buildUnordered(criteria);

    Conjunction conj = Restrictions.conjunction();

    for (Map.Entry<String, String> entry : (Set<Map.Entry<String, String>>) filterMap.entrySet()) {
        // System.out.println(String.format("%s\t%s", entry.getKey(), entry.getValue()));
        String property = entry.getKey();
        String value = entry.getValue();
        if (value == null)
            continue;

        String prop = processProperty(criteria, property);
        Class clazz = PropertyResolver.getPropertyClass(property, beanClass);

        if (String.class.isAssignableFrom(clazz)) {
            String[] items = value.split("\\s+");
            for (String item : items) {
                Disjunction dist = Restrictions.disjunction();
                dist.add(Restrictions.ilike(prop, item, MatchMode.ANYWHERE));
                conj.add(dist);//from  ww w  .  j  a v a  2  s  .c  om
            }
        } else if (Number.class.isAssignableFrom(clazz)) {
            try {
                Matcher matcher = pattern.matcher(value);
                if (matcher.matches()) {
                    String qualifier = matcher.group(2);
                    value = matcher.group(4);
                    Number num = convertToNumber(value, clazz);
                    if (">".equals(qualifier))
                        conj.add(Restrictions.gt(prop, num));
                    else if ("<".equals(qualifier))
                        conj.add(Restrictions.lt(prop, num));
                    else if (">=".equals(qualifier))
                        conj.add(Restrictions.ge(prop, num));
                    else if ("<=".equals(qualifier))
                        conj.add(Restrictions.le(prop, num));
                } else
                    conj.add(Restrictions.eq(prop, convertToNumber(value, clazz)));
            } catch (ConversionException ex) {
                // ignore filter in this case
            }
        } else if (Boolean.class.isAssignableFrom(clazz)) {
            conj.add(Restrictions.eq(prop, Boolean.parseBoolean(value)));
        }
    }
    criteria.add(conj);
}

From source file:net.firejack.platform.core.store.AbstractStore.java

License:Apache License

protected Criterion getRestrictions(SearchQuery query, Class<?> type) {
    Criterion criterion;/*  w ww.j a  v a2 s  . c o  m*/
    Object value = query.getValue();
    QueryOperation operation = query.getOperation();
    if (value != null
            && !(QueryOperation.FIELDEQUALS.equals(operation) || QueryOperation.FIELDNOTEQUALS.equals(operation)
                    || QueryOperation.FIELDGREATERTHAN.equals(operation)
                    || QueryOperation.FIELDLESSTHAN.equals(operation))) {
        if (value instanceof Collection) {
            Collection values = (Collection) value;
            if (Integer.class.equals(type)) {
                List<Integer> list = new ArrayList<Integer>();
                for (Object item : values) {
                    list.add(Integer.parseInt(item.toString()));
                }
                value = list;
            } else if (Long.class.equals(type)) {
                List<Long> list = new ArrayList<Long>();
                for (Object item : values) {
                    list.add(Long.parseLong(item.toString()));
                }
                value = list;
            } else if (java.sql.Date.class.equals(type) || Date.class.equals(type)) {
                List<Date> list = new ArrayList<Date>();
                for (Object item : values) {
                    Tuple<Date, QueryOperation> tuple = convertToDate(item, operation);
                    operation = tuple.getValue();
                    list.add(tuple.getKey());
                }
                value = list;
            } else if (Enum.class.isAssignableFrom(type)) {
                List<Enum> enumValues = new ArrayList<Enum>(values.size());
                for (Object item : values) {
                    Enum enumItem = prepareEnumFromSearchCriteria((Class<? extends Enum>) type, item);
                    enumValues.add(enumItem);
                }
                value = enumValues;
            }
        } else {
            if (Integer.class.equals(type)) {
                value = Integer.parseInt(value.toString());
            } else if (Long.class.equals(type)) {
                value = Long.parseLong(value.toString());
            } else if (Double.class.equals(type)) {
                value = Double.parseDouble(value.toString());
            } else if (java.sql.Date.class.equals(type) || Date.class.equals(type)) {
                Tuple<Date, QueryOperation> tuple = convertToDate(value, operation);
                value = tuple.getKey();
                operation = tuple.getValue();
            } else if (Enum.class.isAssignableFrom(type)) {
                value = prepareEnumFromSearchCriteria((Class<? extends Enum>) type, value);
            }
        }
    }

    if (!String.class.equals(type)
            && (QueryOperation.LIKECS.equals(operation) || QueryOperation.LIKECSFIRST.equals(operation)
                    || QueryOperation.LIKE.equals(operation) || QueryOperation.LIKEFIRST.equals(operation))) {
        operation = QueryOperation.EQUALS;
    }

    switch (operation) {
    case LIKECS:
        criterion = Restrictions.like(query.getField(), "%" + value + "%");
        break;
    case LIKECSFIRST:
        criterion = Restrictions.like(query.getField(), value + "%");
        break;
    case LIKE:
        criterion = Restrictions.ilike(query.getField(), "%" + value + "%");
        break;
    case LIKEFIRST:
        criterion = Restrictions.ilike(query.getField(), value + "%");
        break;
    case EQUALS:
        criterion = Restrictions.eq(query.getField(), value);
        break;
    case LESSTHAN:
        criterion = Restrictions.lt(query.getField(), value);
        break;
    case GREATERTHAN:
        criterion = Restrictions.gt(query.getField(), value);
        break;
    case ISNULL:
        criterion = Restrictions.isNull(query.getField());
        break;
    case ISNOTNULL:
        criterion = Restrictions.isNotNull(query.getField());
        break;
    case ISEMPTY:
        criterion = Restrictions.isEmpty(query.getField());
        break;
    case ISNOTEMPTY:
        criterion = Restrictions.isNotEmpty(query.getField());
        break;
    case NOTEQUALS:
        criterion = Restrictions.ne(query.getField(), value);
        break;
    case IN:
        criterion = generateInRestriction(query.getField(), (Collection) value);
        break;
    case NOTIN:
        criterion = Restrictions.not(generateInRestriction(query.getField(), (Collection) value));
        break;
    case FIELDEQUALS:
        criterion = Restrictions.eqProperty(query.getField(), value != null ? value.toString() : "");
        break;
    case FIELDNOTEQUALS:
        criterion = Restrictions.neProperty(query.getField(), value != null ? value.toString() : "");
        break;
    case FIELDGREATERTHAN:
        criterion = Restrictions.gtProperty(query.getField(), value != null ? value.toString() : "");
        break;
    case FIELDLESSTHAN:
        criterion = Restrictions.ltProperty(query.getField(), value != null ? value.toString() : "");
        break;
    default:
        throw new RuntimeException("Operation " + query.getField() + " is not a valid operation");
    }
    return criterion;
}

From source file:net.firejack.platform.core.store.statistics.LogEntryStore.java

License:Apache License

private List<Criterion> createCriterionsForTermAndDates(String term, String nodeLookup, Date startDate,
        Date endDate, LogEntryType logEntryType) {
    List<Criterion> criterions = new ArrayList<Criterion>();

    if (!StringUtils.isEmpty(term)) {
        Criterion lookupCriterion = Restrictions.like("lookup", "%" + term + "%");
        Criterion usernameCriterion = Restrictions.like("username", "%" + term + "%");
        Criterion detailsCriterion = Restrictions.like("details", "%" + term + "%");
        Criterion termCriterion = Restrictions.or(Restrictions.or(lookupCriterion, usernameCriterion),
                detailsCriterion);//from w  w w  .j  a va 2  s  .c  om
        criterions.add(termCriterion);
    }

    if (!LogEntryType.ALL.equals(logEntryType)) {
        criterions.add(Restrictions.eq("type", logEntryType));
    }

    if (!StringUtils.isEmpty(nodeLookup)) {
        Criterion nodeLookupCriterion = Restrictions.like("lookup", nodeLookup + "%");
        criterions.add(nodeLookupCriterion);
    }

    if (startDate != null) {
        Criterion startDateCriterion = Restrictions.ge("created", startDate);
        criterions.add(startDateCriterion);
    }

    if (endDate != null) {
        Criterion endDateCriterion = Restrictions.lt("created", endDate);
        criterions.add(endDateCriterion);
    }
    return criterions;
}

From source file:net.firejack.platform.core.store.statistics.LogTransactionStore.java

License:Apache License

private List<Criterion> createCriterionsForTermAndDates(String term, String nodeLookup, Date startDate,
        Date endDate) {//from  w  ww.ja v  a2 s  .co m
    List<Criterion> criterions = new ArrayList<Criterion>();

    if (!StringUtils.isEmpty(term)) {
        Criterion termCriterion = Restrictions.sqlRestriction("{alias}.package_lookup LIKE '%" + term + "%'");
        criterions.add(termCriterion);
    }

    if (!StringUtils.isEmpty(nodeLookup)) {
        Criterion nodeLookupCriterion = Restrictions
                .sqlRestriction("{alias}.package_lookup LIKE '" + nodeLookup + "%'");
        criterions.add(nodeLookupCriterion);
    }

    if (startDate != null) {
        Criterion startDateCriterion = Restrictions.ge("created", startDate);
        criterions.add(startDateCriterion);
    }

    if (endDate != null) {
        Criterion endDateCriterion = Restrictions.lt("created", endDate);
        criterions.add(endDateCriterion);
    }
    return criterions;
}

From source file:net.firejack.platform.service.process.broker.ReadPreviousActivitiesBroker.java

License:Apache License

@Override
protected ServiceResponse<Activity> perform(ServiceRequest<NamedValues<Long>> request) throws Exception {
    Long caseId = request.getData().get(PARAM_CASE_ID);
    Long taskId = request.getData().get(PARAM_TASK_ID);
    ServiceResponse<Activity> response;
    if (caseId == null && taskId == null) {
        response = new ServiceResponse<Activity>("taskId or caseId parameter should be specified.", false);
    } else {/*w ww . j a  v a2s.  co m*/
        Integer currentActivityPosition = null;
        ProcessModel process = null;
        if (taskId == null) {
            CaseModel caseModel = caseStore.findById(caseId);
            if (caseModel != null) {
                currentActivityPosition = caseModel.getStatus().getSortPosition();
                process = caseModel.getProcess();
            }
        } else {
            TaskModel taskModel = taskStore.findById(taskId);
            if (taskModel != null) {
                currentActivityPosition = taskModel.getActivity().getSortPosition();
                process = taskModel.getCase().getProcess();
            }
        }
        if (currentActivityPosition == null || process == null) {
            response = new ServiceResponse<Activity>("Wrong taskId or caseId parameter value.", false);
        } else {
            LinkedList<Criterion> criterionList = new LinkedList<Criterion>();
            criterionList.add(Restrictions.and(Restrictions.lt("sortPosition", currentActivityPosition),
                    Restrictions.eq("parent.id", process.getId())));
            List<ActivityModel> previousActivities = store.search(criterionList, null);
            if (previousActivities == null || previousActivities.isEmpty()) {
                response = new ServiceResponse<Activity>("No previous activities are available", true);
            } else {
                Boolean multiBranchStrategySupported = taskCaseProcessor
                        .getMultiBranchStrategy(process.getLookup());
                if (Boolean.TRUE.equals(multiBranchStrategySupported)) {
                    List<Activity> activities = factory.convertTo(Activity.class, previousActivities);
                    response = new ServiceResponse<Activity>(activities, "Success", true);
                } else {
                    Activity activity = factory.convertTo(Activity.class, previousActivities.get(0));
                    response = new ServiceResponse<Activity>(activity, "Success", true);
                }
            }
        }
    }
    return response;
}

From source file:net.longfalcon.newsj.persistence.hibernate.PartRepairDAOImpl.java

License:Open Source License

/**
 * Find by group id and how many attempts its had
 * @param groupId groupid foreign key//from  ww w.  j a  v  a  2  s  .co m
 * @param attempts the number of attempts to look for
 * @param lessThan whether the comparison is less than the attempts or greater than or equal to
 * @return
 */
@Override
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public List<PartRepair> findByGroupIdAndAttempts(long groupId, int attempts, boolean lessThan) {
    Criteria criteria = sessionFactory.getCurrentSession().createCriteria(PartRepair.class)
            .add(Restrictions.eq("groupId", groupId))
            .add(lessThan ? Restrictions.lt("attempts", attempts) : Restrictions.ge("attempts", attempts))
            .addOrder(Order.asc("numberId")).setMaxResults(30000);

    return criteria.list();
}