Example usage for org.hibernate.criterion Restrictions isNotNull

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

Introduction

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

Prototype

public static Criterion isNotNull(String propertyName) 

Source Link

Document

Apply an "is not null" constraint to the named property

Usage

From source file:org.sakaiproject.genericdao.hibernate.HibernateBasicGenericDao.java

License:Apache License

/**
 * Build the Criteria object here to reduce code duplication
 * @param entityClass//from ww  w  . j ava 2  s .  c om
 * @param search a Search object (possibly only partially complete)
 * @return a DetachedCriteria object
 */
private DetachedCriteria buildCriteria(Class<?> entityClass, Search search) {
    // Checks to see if the required params are set and throws exception if not
    if (search == null) {
        throw new IllegalArgumentException("search cannot be null");
    }

    // Build the criteria object
    DetachedCriteria criteria = DetachedCriteria.forClass(entityClass);

    // Only add in restrictions if there are some to add
    if (search.getRestrictions() != null && search.getRestrictions().length > 0) {
        Junction junction = Expression.conjunction(); // AND
        if (!search.conjunction) {
            // set to use disjunction
            junction = Expression.disjunction(); // OR
        }
        criteria.add(junction);

        // put in the restrictions
        for (int i = 0; i < search.getRestrictions().length; i++) {
            String property = search.getRestrictions()[i].property;
            Object value = search.getRestrictions()[i].value;
            if (property == null || value == null) {
                throw new IllegalArgumentException("restrictions property and value cannot be null or empty");
            }
            if (value.getClass().isArray()) {
                // special handling for "in" type comparisons
                Object[] objectArray = (Object[]) value;
                if (objectArray.length == 1) {
                    value = objectArray[0];
                } else if (objectArray.length > 1) {
                    if (Restriction.NOT_EQUALS == search.getRestrictions()[i].comparison) {
                        junction.add(Restrictions.not(Restrictions.in(property, objectArray)));
                    } else {
                        junction.add(Restrictions.in(property, objectArray));
                    }
                } else {
                    // do nothing for now, this is slightly invalid but not worth dying over
                }
            }

            if (!value.getClass().isArray()) {
                switch (search.getRestrictions()[i].comparison) {
                case Restriction.EQUALS:
                    junction.add(Restrictions.eq(property, value));
                    break;
                case Restriction.GREATER:
                    junction.add(Restrictions.gt(property, value));
                    break;
                case Restriction.LESS:
                    junction.add(Restrictions.lt(property, value));
                    break;
                case Restriction.LIKE:
                    junction.add(Restrictions.like(property, value));
                    break;
                case Restriction.NULL:
                    junction.add(Restrictions.isNull(property));
                    break;
                case Restriction.NOT_NULL:
                    junction.add(Restrictions.isNotNull(property));
                    break;
                case Restriction.NOT_EQUALS:
                    junction.add(Restrictions.ne(property, value));
                    break;
                }
            }
        }
    }

    // handle the sorting (sort param can be null for no sort)
    if (search.getOrders() != null) {
        for (int i = 0; i < search.getOrders().length; i++) {
            if (search.getOrders()[i].ascending) {
                criteria.addOrder(org.hibernate.criterion.Order.asc(search.getOrders()[i].property));
            } else {
                criteria.addOrder(org.hibernate.criterion.Order.desc(search.getOrders()[i].property));
            }
        }
    }

    return criteria;
}

From source file:org.sakaiproject.lessonbuildertool.model.SimplePageToolDaoImpl.java

License:Educational Community License

public List<SimplePageLogEntry> getStudentPageLogEntries(long itemId, String userId) {
    DetachedCriteria d = DetachedCriteria.forClass(SimplePageLogEntry.class)
            .add(Restrictions.eq("userId", userId)).add(Restrictions.eq("itemId", itemId))
            .add(Restrictions.isNotNull("studentPageId"));

    List<SimplePageLogEntry> entries = getHibernateTemplate().findByCriteria(d);

    return entries;
}

From source file:org.sculptor.framework.accessimpl.jpahibernate.JpaHibFindByConditionAccessImpl.java

License:Apache License

private Criterion makeCriterion(ConditionalCriteria crit) {
    if (crit == null) {
        return null;
    }//w  ww.  jav  a 2  s.  c o  m

    ConditionalCriteria.Operator operator = crit.getOperator();
    if (Operator.Equal.equals(operator)) {
        return Restrictions.eq(makePathWithAlias(crit.getPropertyFullName()), crit.getFirstOperant());
    } else if (Operator.IgnoreCaseEqual.equals(operator)) {
        return Restrictions.eq(makePathWithAlias(crit.getPropertyFullName()), crit.getFirstOperant())
                .ignoreCase();
    } else if (Operator.LessThan.equals(operator)) {
        return Restrictions.lt(makePathWithAlias(crit.getPropertyFullName()), crit.getFirstOperant());
    } else if (Operator.LessThanOrEqual.equals(operator)) {
        return Restrictions.le(makePathWithAlias(crit.getPropertyFullName()), crit.getFirstOperant());
    } else if (Operator.GreatThan.equals(operator)) {
        return Restrictions.gt(makePathWithAlias(crit.getPropertyFullName()), crit.getFirstOperant());
    } else if (Operator.GreatThanOrEqual.equals(operator)) {
        return Restrictions.ge(makePathWithAlias(crit.getPropertyFullName()), crit.getFirstOperant());
    } else if (Operator.Like.equals(operator)) {
        // Hibernate bug HHH-5339 + PostgreSQL missing 'number like string' conversion
        return new NumericLikeExpression(makePathWithAlias(crit.getPropertyFullName()),
                crit.getFirstOperant().toString(), false);
    } else if (Operator.IgnoreCaseLike.equals(operator)) {
        // Hibernate bug HHH-5339 + PostgreSQL missing 'number like string' conversion
        return new NumericLikeExpression(makePathWithAlias(crit.getPropertyFullName()),
                crit.getFirstOperant().toString(), true);
    } else if (Operator.IsNull.equals(operator)) {
        return Restrictions.isNull(makePathWithAlias(crit.getPropertyFullName()));
    } else if (Operator.IsNotNull.equals(operator)) {
        return Restrictions.isNotNull(makePathWithAlias(crit.getPropertyFullName()));
    } else if (Operator.IsEmpty.equals(operator)) {
        return Restrictions.isEmpty(makePathWithAlias(crit.getPropertyFullName()));
    } else if (Operator.IsNotEmpty.equals(operator)) {
        return Restrictions.isNotEmpty(makePathWithAlias(crit.getPropertyFullName()));
    } else if (Operator.Not.equals(operator)) {
        return Restrictions.not(makeCriterion((ConditionalCriteria) crit.getFirstOperant()));
    } else if (Operator.Or.equals(operator) && crit.getFirstOperant() instanceof List<?>) {
        Disjunction disj = Restrictions.disjunction();
        List<?> disjList = (List<?>) crit.getFirstOperant();
        for (Object disjPart : disjList) {
            disj.add(makeCriterion((ConditionalCriteria) disjPart));
        }
        return disj;
    } else if (Operator.Or.equals(operator)) {
        return Restrictions.or(makeCriterion((ConditionalCriteria) crit.getFirstOperant()),
                makeCriterion((ConditionalCriteria) crit.getSecondOperant()));
    } else if (Operator.And.equals(operator) && crit.getFirstOperant() instanceof List<?>) {
        Conjunction conj = Restrictions.conjunction();
        List<?> conjList = (List<?>) crit.getFirstOperant();
        for (Object conjPart : conjList) {
            conj.add(makeCriterion((ConditionalCriteria) conjPart));
        }
        return conj;
    } else if (Operator.And.equals(operator)) {
        return Restrictions.and(makeCriterion((ConditionalCriteria) crit.getFirstOperant()),
                makeCriterion((ConditionalCriteria) crit.getSecondOperant()));
    } else if (Operator.In.equals(operator)) {
        if (crit.getFirstOperant() instanceof Collection<?>) {
            return Restrictions.in(makePathWithAlias(crit.getPropertyFullName()),
                    (Collection<?>) crit.getFirstOperant());
        } else {
            return Restrictions.in(makePathWithAlias(crit.getPropertyFullName()),
                    (Object[]) crit.getFirstOperant());
        }
    } else if (Operator.Between.equals(operator)) {
        return Restrictions.between(makePathWithAlias(crit.getPropertyFullName()), crit.getFirstOperant(),
                crit.getSecondOperant());
    } else if (Operator.DistinctRoot.equals(operator)) {
        realDistinctRoot = true;
        return null;
    } else if (Operator.ProjectionRoot.equals(operator)) {
        resultTransformer = Criteria.PROJECTION;
        return null;
    } else if (Operator.EqualProperty.equals(operator)) {
        return Restrictions.eqProperty(makePathWithAlias(crit.getPropertyFullName()),
                (String) crit.getFirstOperant());
    } else if (Operator.LessThanProperty.equals(operator)) {
        return Restrictions.ltProperty(makePathWithAlias(crit.getPropertyFullName()),
                (String) crit.getFirstOperant());
    } else if (Operator.LessThanOrEqualProperty.equals(operator)) {
        return Restrictions.leProperty(makePathWithAlias(crit.getPropertyFullName()),
                (String) crit.getFirstOperant());
    } else if (Operator.GreatThanProperty.equals(operator)) {
        return Restrictions.gtProperty(makePathWithAlias(crit.getPropertyFullName()),
                (String) crit.getFirstOperant());
    } else if (Operator.GreatThanOrEqualProperty.equals(operator)) {
        return Restrictions.geProperty(makePathWithAlias(crit.getPropertyFullName()),
                (String) crit.getFirstOperant());
    } else {
        return null;
    }
}

From source file:org.shredzone.cilla.core.repository.impl.PageDaoHibImpl.java

License:Open Source License

@Transactional(readOnly = true)
@Override//  w w w.ja  v a 2 s .c om
public Date[] fetchMinMaxModification() {
    Date now = new Date();

    Criteria crit = getCurrentSession().createCriteria(Page.class);

    crit.add(Restrictions.and(Restrictions.isNotNull("publication"), Restrictions.le("publication", now)));

    crit.add(Restrictions.or(Restrictions.isNull("expiration"), Restrictions.gt("expiration", now)));

    crit.add(Restrictions.eq("hidden", false));

    ProjectionList proj = Projections.projectionList();
    proj.add(Projections.min(pageOrder.getColumn()));
    proj.add(Projections.max(pageOrder.getColumn()));
    crit.setProjection(proj);
    Object[] row = (Object[]) crit.uniqueResult();

    Date[] result = new Date[2];
    result[0] = (Date) row[0];
    result[1] = (Date) row[1];
    return result;
}

From source file:org.shredzone.cilla.service.impl.TagServiceImpl.java

License:Open Source License

@SuppressWarnings("unchecked")
@Transactional(readOnly = true)/*from   w w w  . j  a  va  2  s. c o m*/
@Cacheable("tagCloud")
@Override
public Map<Tag, Float> createTagCloud(long limit) {
    Date now = new Date();
    Date limitDate = new Date(now.getTime() - limit);

    List<Page> pages = pageDao.criteria()
            .add(Restrictions.and(Restrictions.isNotNull("publication"),
                    Restrictions.between("publication", limitDate, now)))
            .add(Restrictions.or(Restrictions.isNull("expiration"), Restrictions.gt("expiration", now)))
            .add(Restrictions.isNotEmpty("tags")).list();

    return computeTagCloud(pages, limitDate.getTime(), limit);
}

From source file:org.shredzone.cilla.service.search.strategy.AbstractSearchStrategy.java

License:Open Source License

/**
 * Creates a {@link Criteria} object for the filter given in the
 * {@link SearchResultImpl}.//from  www  .  j  a  va  2 s .  c  o m
 */
protected Criteria createCriteria(SearchResultImpl result) throws CillaServiceException {
    Criteria crit = pageDao.criteria();
    crit.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);

    crit.add(Restrictions.and(Restrictions.isNotNull("publication"),
            Restrictions.le("publication", result.getNow())));

    crit.add(
            Restrictions.or(Restrictions.isNull("expiration"), Restrictions.gt("expiration", result.getNow())));

    crit.add(Restrictions.eq("hidden", false));

    FilterModel filter = result.getFilter();
    if (filter != null) {
        if (filter.getCategory() != null) {
            // I'd prefer to use Restrictions.in instead, but this seems to be difficult.
            // http://stackoverflow.com/questions/407737/hibernate-criteria-querying-tables-in-nm-relationship
            Disjunction dis = Restrictions.disjunction();
            result.getEffectiveCategories().stream().mapToLong(Category::getId)
                    .forEach(id -> dis.add(Restrictions.idEq(id)));
            crit.createCriteria("categories").add(dis);
        }

        if (filter.getTag() != null) {
            long tagId = filter.getTag().getId();
            Disjunction dis = Restrictions.disjunction();

            // All pages with the requested tag
            crit.createAlias("tags", "tt");
            dis.add(Restrictions.eq("tt.id", tagId));

            // All pages with pictures in a gallery section having the requested tag
            DetachedCriteria subcrit = DetachedCriteria.forClass(GallerySection.class);
            subcrit.createCriteria("pictures").createCriteria("tags").add(Restrictions.idEq(tagId));
            subcrit.setProjection(Projections.distinct(Projections.property("page.id")));
            dis.add(Subqueries.propertyIn("id", subcrit));

            crit.add(dis);
        }

        if (filter.getCreator() != null) {
            crit.add(Restrictions.eq("creator", filter.getCreator()));
        }

        if (filter.getPage() != null) {
            crit.add(Restrictions.idEq(filter.getPage().getId()));
        }

        if (filter.getDate() != null) {
            DateRange dr = filter.getDate();
            PageOrder order = (filter.getOrder() != null ? filter.getOrder() : PageOrder.PUBLICATION);
            crit.add(Restrictions.between(order.getColumn(), dr.getFromDate().getTime(),
                    dr.getThruDate().getTime()));
        }

        if (filter.getQuery() != null) {
            // No challenge protected pages for context search, because protected
            // contents may be revealed in the search results.
            crit.add(Restrictions.isNull("challenge"));
        }
    }

    return crit;
}

From source file:org.traffic.server.handler.UpdateHandler.java

License:Open Source License

@SuppressWarnings("unchecked")
@Override/*from  w ww  .j a v a2  s.  c  o m*/
public void handleRequest(Request r) {

    // check if the client has a valid identification
    if (r.getClient() == null) {
        SocketCommunicator.writeOutput(getSocket(), "{'error': 'no valid identification'}");
        Log.e("UpdateHandler", "Error@handleRequest:no valid identification");
        return;
    }
    Session s = Database.session();
    s.beginTransaction();

    // getting the data of the client
    if (r.getData().containsKey("lat") && r.getData().containsKey("lon") && r.getData().containsKey("time")
            && r.getData().containsKey("speed")) {
        int bboxType = Integer.valueOf(r.getData().getString("bbox"));
        double lat = r.getData().getDouble("lat");
        double lon = r.getData().getDouble("lon");
        long time = r.getData().getLong("time");
        double speed = r.getData().getDouble("speed");
        boolean save = true;
        if (r.getData().containsKey("save")) {
            save = r.getData().getBoolean("save");
        }
        String hash = r.getID();
        Point p = GeomHelper.createPoint(lon, lat);
        UserData d = new UserData(new Date(time), p, speed, hash);

        // building the response
        Response res = new Response();
        RoadStrip rs = (RoadStrip) s.createCriteria(RoadStrip.class)
                .add(new DWithinExpression("way", p, 8.2E-4)).addOrder(LocalDistanceOrder.asc("distance", p))
                .setMaxResults(1).uniqueResult();

        if (rs != null) {
            List<UserData> prevData = (List<UserData>) s.createCriteria(UserData.class)
                    .add(Restrictions.eq("connectionhash", r.getID()))
                    .add(Restrictions.lt("time", new Date(time))).add(Restrictions.isNotNull("road_id"))
                    .addOrder(Order.desc("time")).list();

            // getting the driving direction
            boolean driveDirection = false;
            if (prevData.size() > 0) {
                UserData prev = prevData.get(0);
                if (prev.getRoad_id() == rs.getId()) {
                    driveDirection = (prev.getPosition().distance(rs.getWay().getStartPoint()) < d.getPosition()
                            .distance(rs.getWay().getStartPoint()));
                } else {
                    driveDirection = (prev.getPosition().distance(rs.getWay().getStartPoint()) > prev
                            .getPosition().distance(rs.getWay().getEndPoint()));
                }
            }

            // adding the current road to the response
            d.setRoad_id(rs.getId());
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("id", rs.getId());
            int max = (rs.getRoad().getMaxspeed() != null) ? rs.getRoad().getMaxspeed() : 0;
            map.put("maxspeed", max);
            map.put("speed", rs.getBestSpeed(driveDirection).getSpeed());
            map.put("quality", rs.getBestSpeed(driveDirection).getCategory());
            res.append(map, "traffic");

            // surrounding congestions of the current road
            List<Congestion> congestions = new LinkedList<Congestion>();
            congestions.addAll(rs.getCongestions());

            if (bboxType != 1) {
                // adding all known neighbours to the response
                Criteria crit = s.createCriteria(RoadStrip.class).add(Restrictions.ne("id", rs.getId()));
                if (bboxType == 2) {
                    crit.add(SpatialRestrictions.intersects("way", rs.getWay()));
                } else {
                    crit.add(SpatialRestrictions.intersects("way", GeomHelper.createRectangle(p, 2000)));
                }

                List<RoadStrip> neighbours = (List<RoadStrip>) crit.list();
                // adding the neighbors to the output
                for (RoadStrip neighbour : neighbours) {
                    boolean direction = neighbour.getWay().getStartPoint().intersects(rs.getWay());
                    map = new HashMap<String, Object>();
                    map.put("id", neighbour.getId());
                    max = (neighbour.getRoad().getMaxspeed() != null) ? neighbour.getRoad().getMaxspeed() : 0;
                    map.put("maxspeed", max);
                    map.put("speed", neighbour.getBestSpeed(direction).getSpeed());
                    map.put("quality", neighbour.getBestSpeed(direction).getCategory());
                    res.append(map, "traffic");

                    // congestions of the neighbor
                    congestions.addAll(neighbour.getCongestions());
                }
            }

            // sending congestions to the client
            for (Congestion c : congestions) {
                map = new HashMap<String, Object>();
                map.put("lon", c.getPosition().getX());
                map.put("lat", c.getPosition().getY());
                map.put("type", c.getType());
                map.put("time", c.getReportingtime().getTime());
                map.put("id", c.getId());
                res.append(map, "congestions");
            }
        }

        // check if a route is active and has changed since the last request
        if (r.getClient().getRoute() != null && r.getClient().getRoute().isUpdated()) {
            res.append(true, "routing");
        }

        // send, clear and save
        SocketCommunicator.writeOutput(getSocket(), res.getData());
        if (save) {
            s.clear();
            s.save(d);
            Database.end(true);
        } else {
            Database.end(false);
        }
    } else {
        SocketCommunicator.writeOutput(getSocket(), "{error: 'missing arguments'}");
    }
}

From source file:org.wise.portal.dao.peerreview.impl.HibernatePeerReviewGateDao.java

License:Open Source License

@Transactional(readOnly = true)
private List<PeerReviewWork> getPeerReviewWorkByRunPeriodNode(Long runId, Long periodId, Node node) {
    Session session = this.getHibernateTemplate().getSessionFactory().getCurrentSession();
    List<PeerReviewWork> result = session.createCriteria(PeerReviewWork.class)
            .add(Restrictions.eq("runId", runId)).add(Restrictions.eq("periodId", periodId))
            .add(Restrictions.eq("node", node)).add(Restrictions.isNotNull("stepWork")).list();
    return result;
}

From source file:org.wise.portal.dao.peerreview.impl.HibernatePeerReviewWorkDao.java

License:Open Source License

@Transactional(readOnly = true)
public List<PeerReviewWork> getPeerReviewWorkByRunPeriodNode(Long runId, Long periodId, Node node) {
    Session session = this.getHibernateTemplate().getSessionFactory().getCurrentSession();
    List<PeerReviewWork> result = session.createCriteria(PeerReviewWork.class)
            .add(Restrictions.eq("runId", runId)).add(Restrictions.eq("periodId", periodId))
            .add(Restrictions.eq("node", node)).add(Restrictions.isNotNull("stepWork")).list();
    return result;
}