Example usage for org.hibernate.criterion Restrictions disjunction

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

Introduction

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

Prototype

public static Disjunction disjunction() 

Source Link

Document

Group expressions together in a single disjunction (A or B or C...).

Usage

From source file:org.goobi.production.flow.statistics.hibernate.FilterHelper.java

License:Open Source License

/**
 * limit query to project (formerly part of ProzessverwaltungForm).
 *//*  ww  w  .  j av a  2  s  . co m*/
protected static void limitToUserAccessRights(Conjunction con) {
    /* restriction to specific projects if not with admin rights */
    LoginForm loginForm = (LoginForm) Helper.getManagedBeanValue("#{LoginForm}");
    User aktuellerNutzer = null;
    try {
        if (loginForm != null && loginForm.getMyBenutzer() != null) {
            aktuellerNutzer = serviceManager.getUserService().find(loginForm.getMyBenutzer().getId());
        }
    } catch (DAOException e) {
        logger.warn("DAOException", e);
    } catch (Exception e) {
        logger.trace("Exception", e);
    }
    if (aktuellerNutzer != null) {
        if (loginForm.getMaximaleBerechtigung() > 1) {
            Disjunction dis = Restrictions.disjunction();
            for (Project proj : aktuellerNutzer.getProjects()) {
                dis.add(Restrictions.eq("project", proj));
            }
            con.add(dis);
        }
    }
}

From source file:org.grails.datastore.gorm.hibernate.query.HibernateQuery.java

License:Apache License

@Override
public Junction negation() {
    final org.hibernate.criterion.Disjunction disjunction = Restrictions.disjunction();
    criteria.add(Restrictions.not(disjunction));

    return new HibernateJunction(disjunction);
}

From source file:org.hyperic.hq.authz.server.session.AuthzSubjectDAO.java

License:Open Source License

public Collection findAll_order(boolean isRoot, String col, boolean asc, Collection excludes) {
    Criteria criteria = createCriteria();

    if (isRoot) {
        Disjunction disjunctions = Restrictions.disjunction();
        disjunctions.add(Restrictions.eq("system", Boolean.FALSE));
        disjunctions.add(Restrictions.eq("id", AuthzConstants.rootSubjectId));
        criteria.add(disjunctions);// w w  w.j av a2 s  . c  o  m
    } else {
        criteria.add(Restrictions.eq("system", Boolean.FALSE));
    }

    criteria.addOrder(asc ? Order.asc(col) : Order.desc(col));

    if (excludes != null && excludes.size() > 0) {
        criteria.add(Restrictions.not(Restrictions.in("id", excludes)));
    }

    return criteria.list();

}

From source file:org.infoglue.calendar.controllers.EntryController.java

License:Open Source License

/**
 * Gets a list of all entrys available sorted by primary key.
 * @return List of Entry/*from w w  w.j av  a2  s .com*/
 * @throws Exception
 */

public Set getEntryList(String userName, List roles, List groups, Long[] eventId, String firstName,
        String lastName, String email, boolean onlyFutureEvents, Map selectedCategoryAttributes,
        boolean andSearch, Session session) throws Exception {
    List result = null;

    Criteria criteria = session.createCriteria(Entry.class);

    Criteria eventCriteria = criteria.createCriteria("event");
    Criteria calendarCriteria = eventCriteria.createCriteria("owningCalendar");

    calendarCriteria.createCriteria("owningRoles").add(Expression.in("name", roles.toArray()));
    if (groups.size() > 0)
        calendarCriteria.createCriteria("owningGroups").add(Expression.in("name", groups.toArray()));

    if (onlyFutureEvents)
        eventCriteria.add(Expression.gt("endDateTime", java.util.Calendar.getInstance()));

    if (selectedCategoryAttributes != null && selectedCategoryAttributes.size() > 0) {
        Criteria eventCategoriesCriteria = eventCriteria.createCriteria("eventCategories");
        Criteria categoryAttributesCriteria = eventCategoriesCriteria
                .createCriteria("eventTypeCategoryAttribute");
        Criteria categoryCriteria = eventCategoriesCriteria.createCriteria("category");

        Junction junction = Restrictions.disjunction();
        if (andSearch)
            junction = Restrictions.conjunction();

        eventCategoriesCriteria.add(junction);

        Iterator selectedCategoryAttributesIterator = selectedCategoryAttributes.keySet().iterator();
        while (selectedCategoryAttributesIterator.hasNext()) {
            String id = (String) selectedCategoryAttributesIterator.next();
            Long[] categories = (Long[]) selectedCategoryAttributes.get(id);
            log.info("id:" + id);
            log.info("categories:" + categories);
            if (categories != null) {
                Criterion e1 = Restrictions.eq("eventTypeCategoryAttribute.id", new Long(id));
                Criterion e2 = Restrictions.in("category.id", categories);
                Criterion criterion = Restrictions.and(e1, e2);

                junction.add(criterion);
            }
        }
        log.info("junction:" + junction.toString());
    }

    //        if(eventId != null)
    //           eventCriteria.add(Restrictions.idEq(eventId));

    if (eventId != null && eventId.length > 0 && eventId[0] != null)
        eventCriteria.add(Restrictions.in("id", eventId));

    if (firstName != null && firstName.length() != 0)
        criteria.add(Restrictions.like("firstName", firstName));
    if (lastName != null && lastName.length() != 0)
        criteria.add(Restrictions.like("lastName", lastName));
    if (email != null && email.length() != 0)
        criteria.add(Restrictions.like("email", email));

    criteria.addOrder(Order.asc("id"));

    Set set = new LinkedHashSet();
    set.addAll(criteria.list());

    return set;
}

From source file:org.infoglue.calendar.controllers.EventController.java

License:Open Source License

/**
 * Gets a list of all events available for a particular calendar with the optional categories.
 * @param categories The Map should have the form: key = EventType's categoryattribute name, value = list of Category.internalNames to match against
 * @return List of Event//  w w w  .  j  a  va  2s  .  com
 * @throws Exception
 */
public Set getEventList(String[] calendarIds, Map<String, String[]> categories, String includedLanguages,
        java.util.Calendar startCalendar, java.util.Calendar endCalendar, String freeText,
        Integer numberOfItems, Session session) throws Exception {
    List result = null;

    String calendarSQL = null;
    if (calendarIds != null && calendarIds.length > 0) {
        calendarSQL = "(";
        for (int i = 0; i < calendarIds.length; i++) {
            String calendarIdString = calendarIds[i];

            try {
                Integer calendarId = new Integer(calendarIdString);
            } catch (Exception e) {
                log.warn("An invalid calendarId was given:" + e.getMessage());
                return null;
            }

            if (i > 0)
                calendarSQL += ",";

            calendarSQL += calendarIdString;
        }
        calendarSQL += ")";
    } else {
        return null;
    }

    Object[] calendarIdArray = new Object[calendarIds.length];
    for (int i = 0; i < calendarIds.length; i++)
        calendarIdArray[i] = new Long(calendarIds[i]);

    Set set = new LinkedHashSet();

    if (calendarIdArray.length > 0) {
        Criteria criteria = session.createCriteria(Event.class);
        criteria.add(Expression.eq("stateId", Event.STATE_PUBLISHED));

        Criteria versionsCriteria = criteria.createAlias("versions", "v");

        if (startCalendar != null && endCalendar != null) {
            if (startCalendar.get(java.util.Calendar.YEAR) == endCalendar.get(java.util.Calendar.YEAR)
                    && startCalendar.get(java.util.Calendar.DAY_OF_YEAR) == endCalendar
                            .get(java.util.Calendar.DAY_OF_YEAR)) {
                startCalendar.set(java.util.Calendar.HOUR_OF_DAY, 23);
                endCalendar.set(java.util.Calendar.HOUR_OF_DAY, 1);
                criteria.add(Expression.and(Expression.le("startDateTime", startCalendar),
                        Expression.ge("endDateTime", endCalendar)));
            } else {
                criteria.add(Expression.or(
                        Expression.and(Expression.ge("startDateTime", startCalendar),
                                Expression.le("startDateTime", endCalendar)),
                        Expression.and(Expression.ge("endDateTime", endCalendar),
                                Expression.le("endDateTime", endCalendar))));
            }
        } else {
            criteria.add(Expression.gt("endDateTime", java.util.Calendar.getInstance()));
        }

        criteria.add(Expression.eq("stateId", Event.STATE_PUBLISHED));
        criteria.addOrder(Order.asc("startDateTime"));
        criteria.createCriteria("calendars").add(Expression.in("id", calendarIdArray));

        if (log.isInfoEnabled()) {
            StringBuilder sb = null;
            if (categories != null) {
                sb = new StringBuilder();
                sb.append("{");
                for (Map.Entry<String, String[]> category : categories.entrySet()) {
                    if (category.getKey() != null) {
                        sb.append(category.getKey());
                        sb.append("=");
                        sb.append(Arrays.toString(category.getValue()));
                        sb.append(", ");
                    } else {
                        sb.append("--null-key--, ");
                    }
                }
                // Remove extra comma
                if (categories.size() > 0)
                    sb.delete(sb.length() - 2, sb.length());
                sb.append("}");
            }
            log.info("categories:" + sb);
        }
        if (categories != null && categories.size() > 0) {
            List<DetachedCriteria> eventCategoryCriterias = new LinkedList<DetachedCriteria>();
            for (Map.Entry<String, String[]> entry : categories.entrySet()) {
                DetachedCriteria dc = DetachedCriteria.forClass(EventCategory.class, "ec")
                        .setProjection(Property.forName("event.id"))
                        .createAlias("ec.eventTypeCategoryAttribute", "etca").createAlias("ec.category", "cat");

                Conjunction cas = Restrictions.conjunction();
                boolean include = false;
                if (entry.getKey() != null && !"".equals(entry.getKey())) // empty string means categoryAttribute was not defined
                {
                    log.debug("Adding category internal name: " + entry.getKey());
                    cas.add(Property.forName("etca.internalName").eq(entry.getKey()));
                    include = true;
                } else if (log.isInfoEnabled()) {
                    log.info(
                            "Got no category attribute. Will search for provided categorys in all category keys.");
                }
                if (entry.getValue() != null && entry.getValue().length > 0) {
                    log.debug("Category values: " + Arrays.toString(entry.getValue()));
                    if (entry.getValue().length == 1 && "".equals(entry.getValue()[0])) {
                        log.debug("Category value list was empty will not add criteria");
                        continue;
                    }
                    cas.add(Property.forName("cat.internalName").in(entry.getValue()));
                    include = true;
                }
                if (include) {
                    dc.add(cas);
                    eventCategoryCriterias.add(dc);
                }
            }
            for (DetachedCriteria dc : eventCategoryCriterias) {
                criteria.add(Subqueries.propertyIn("id", dc));
            }
        }

        Criteria languageVersionCriteria = null;
        log.info("includedLanguages:" + includedLanguages);
        if (includedLanguages != null && !includedLanguages.equalsIgnoreCase("")
                && !includedLanguages.equalsIgnoreCase("*")) {
            //languageVersionCriteria = criteria.createCriteria("versions");
            versionsCriteria.createCriteria("v.language").add(Expression.eq("isoCode", includedLanguages));
        }

        if (freeText != null && !freeText.equals("")) {
            Criterion nameRestriction = Restrictions.like("name", "%" + freeText + "%");
            Criterion organizerNameRestriction = Restrictions.like("organizerName", "%" + freeText + "%");

            Junction d1 = Restrictions.disjunction().add(Restrictions.like("v.name", "%" + freeText + "%"))
                    .add(Restrictions.like("v.description", "%" + freeText + "%"))
                    .add(Restrictions.like("v.lecturer", "%" + freeText + "%"))
                    .add(Restrictions.like("v.longDescription", "%" + freeText + "%"))
                    .add(Restrictions.like("v.shortDescription", "%" + freeText + "%"))
                    .add(Restrictions.like("v.organizerName", "%" + freeText + "%"))
                    .add(Restrictions.like("v.customLocation", "%" + freeText + "%"))
                    .add(Restrictions.like("v.eventUrl", "%" + freeText + "%"))
                    .add(Restrictions.like("v.alternativeLocation", "%" + freeText + "%"))
                    .add(Restrictions.like("name", "%" + freeText + "%"))
                    .add(Restrictions.like("description", "%" + freeText + "%"))
                    .add(Restrictions.like("contactName", "%" + freeText + "%"))
                    .add(Restrictions.like("lecturer", "%" + freeText + "%"))
                    .add(Restrictions.like("longDescription", "%" + freeText + "%"))
                    .add(Restrictions.like("contactEmail", "%" + freeText + "%"))
                    .add(Restrictions.like("shortDescription", "%" + freeText + "%"))
                    .add(Restrictions.like("organizerName", "%" + freeText + "%"))
                    .add(Restrictions.like("contactPhone", "%" + freeText + "%"))
                    .add(Restrictions.like("price", "%" + freeText + "%"))
                    .add(Restrictions.like("customLocation", "%" + freeText + "%"))
                    .add(Restrictions.like("eventUrl", "%" + freeText + "%"))
                    .add(Restrictions.like("alternativeLocation", "%" + freeText + "%"));

            criteria.add(d1);
        }

        if (numberOfItems != null)
            criteria.setMaxResults(numberOfItems);

        result = criteria.list();

        log.info("result:" + result.size());

        set.addAll(result);
    }

    return set;
}

From source file:org.jasig.ssp.dao.PersonSearchDao.java

License:Apache License

/**
 * Search people by the specified terms.
 * //from   w  ww .ja  v  a  2 s.  c o m
 * @param programStatus
 *            program status filter
 * @param requireProgramStatus
 *            implicitly <code>true</code> if <code>programStatus</code> is
 *            non-null. Else <code>false</code> allows searching without
 *            requiring a program status; defaults to <code>true</code>
 * @param outsideCaseload
 *            false allows searches without checking the Coach (advisor)
 *            property; defaults to true
 * @param searchTerm
 *            Search term that search first and last name and school ID;
 *            required
 * @param advisor
 *            required if outsideCaseload is not {@link Boolean#FALSE}.
 * @param sAndP
 *            Sorting and paging parameters
 * @return List of people that match the specified filters
 */
public PagingWrapper<Person> searchBy(@NotNull final ProgramStatus programStatus,
        final Boolean requireProgramStatus, final Boolean outsideCaseload, @NotNull final String searchTerm,
        final Person advisor, final SortingAndPaging sAndP) {

    if (StringUtils.isBlank(searchTerm)) {
        throw new IllegalArgumentException("search term must be specified");
    }

    final Criteria query = createCriteria();

    boolean isRequiringProgramStatus = programStatus != null || requireProgramStatus == null
            || Boolean.TRUE.equals(requireProgramStatus);
    JoinType programStatusJoinType = isRequiringProgramStatus ? JoinType.INNER_JOIN : JoinType.LEFT_OUTER_JOIN;
    query.createAlias("programStatuses", "personProgramStatus", programStatusJoinType);

    if (programStatus != null) {
        query.add(Restrictions.eq("personProgramStatus.programStatus", programStatus));
    }

    if ((sAndP != null) && sAndP.isFilteredByStatus()) {
        query.add(Restrictions.isNull("personProgramStatus.expirationDate"));
    }

    if (Boolean.FALSE.equals(outsideCaseload)) {
        query.add(Restrictions.eq("coach", advisor));
    }

    // searchTerm : Can be firstName, lastName, studentId or firstName + ' '
    // + lastName
    final Disjunction terms = Restrictions.disjunction();

    final String searchTermLowercase = searchTerm.toLowerCase(Locale.getDefault());
    terms.add(Restrictions.ilike("firstName", searchTermLowercase, MatchMode.ANYWHERE));
    terms.add(Restrictions.ilike("lastName", searchTermLowercase, MatchMode.ANYWHERE));
    terms.add(Restrictions.ilike("schoolId", searchTermLowercase, MatchMode.ANYWHERE));

    terms.add(Restrictions.sqlRestriction(
            "lower({alias}.first_name) " + configService.getDatabaseConcatOperator() + " ' ' "
                    + configService.getDatabaseConcatOperator() + " lower({alias}.last_name) like ? ",
            searchTermLowercase, new StringType()));

    query.add(terms);

    // eager load program status
    query.setFetchMode("personProgramStatus", FetchMode.JOIN);
    query.setFetchMode("personProgramStatus.programStatus", FetchMode.JOIN);

    final PagingWrapper<Object[]> results = processCriteriaWithSortingAndPaging(query, sAndP, true);

    final List<Person> people = Lists.newArrayList();
    for (Object[] personAndProgramStatus : results) {
        if ((personAndProgramStatus != null) && (personAndProgramStatus.length > 0)) {
            if (personAndProgramStatus[0] instanceof Person) {
                people.add((Person) personAndProgramStatus[0]);
            } else if (personAndProgramStatus[1] instanceof Person) {
                people.add((Person) personAndProgramStatus[1]);
            }
        }
    }

    return new PagingWrapper<Person>(results.getResults(), people);
}

From source file:org.jnap.core.persistence.hibernate.DynaQueryBuilder.java

License:Apache License

public Criteria build() throws QueryException {
    Matcher matcher = DYNA_QUERY_PATTERN.matcher(this.dynaQuery);
    if (!matcher.matches()) {
        throw new QueryException("The QueryMethod syntax is incorrect. It must start with 'findBy' "
                + ", findUniqueBy or 'countBy' expression followed by property expressions and operators.",
                this.dynaQuery);
    }/*from  ww w. j  a v  a  2s  .co m*/
    Criteria criteria = this.createCriteria(matcher.group(1).equals("countBy"));
    String dynaQueryExpression = matcher.group(2);

    // order by
    Matcher orderByMatcher = ORDER_BY_PATTERN.matcher(dynaQueryExpression);
    if (orderByMatcher.find()) {
        dynaQueryExpression = StringUtils.remove(dynaQueryExpression, orderByMatcher.group());
        String orderByProperty = normalizePropertyName(orderByMatcher.group(3));
        String orderByDirection = orderByMatcher.group(4);
        Order orderBy = "Desc".equals(orderByDirection) ? Order.desc(orderByProperty)
                : Order.asc(orderByProperty);
        criteria.addOrder(orderBy);
    }

    // split properties
    String[] properties = DYNA_QUERY_OPERATOR_PATTERN.split(dynaQueryExpression);
    if (properties.length == 0 || properties.length > 2) {
        throw new QueryException(format(
                "The QueryMethod syntax is incorrect. Dynamic queries must have "
                        + "at least one property an no more than two (yours has {0}).\nYou can use one of "
                        + "the following logical operators ({1}) and these expression operators ({2})",
                properties.length, LOGICAL_OPERATOR_AND + ", " + LOGICAL_OPERATOR_OR,
                StringUtils.join(EXPRESSION_OPERATORS, ", ")), this.dynaQuery);
    }
    Matcher logicalOperatorsMatcher = DYNA_QUERY_OPERATOR_PATTERN.matcher(dynaQueryExpression);
    String logicalOperator = logicalOperatorsMatcher.find() ? logicalOperatorsMatcher.group(1)
            : LOGICAL_OPERATOR_AND;
    Junction junction = LOGICAL_OPERATOR_OR.equals(logicalOperator) ? Restrictions.disjunction()
            : Restrictions.conjunction();
    for (String property : properties) {
        junction.add(this.createCriterion(property));
    }
    criteria.add(junction);
    return criteria;
}

From source file:org.josescalia.common.dao.impl.CommonDaoImpl.java

public List<T> getDataTablePaginatedList(Map<String, Object> mapParam, int startRow, int lengthRow)
        throws Exception {
    T t = null;/*ww w  .j  av a2s .c  o  m*/
    try {
        t = clazz.newInstance();
    } catch (InstantiationException e) {
        throw new Exception(e);
    } catch (IllegalAccessException e) {
        throw new Exception(e);
    }

    List<T> rList = new ArrayList<T>();
    Criteria criteria = getCurrentSession().createCriteria(t.getClass());

    if (mapParam != null) {
        Disjunction or = Restrictions.disjunction();
        for (Object key : mapParam.keySet()) {
            logger.info(key + " : " + mapParam.get(key));
            String field = key.toString();
            Object value = mapParam.get(key);
            //must filter by id
            if (field.equalsIgnoreCase("id")) {
                try {
                    or.add(Restrictions.eq(field, new Long(value.toString())));
                } catch (Exception e) {
                    logger.error("Cannot cast " + value + " to Long data type");
                }
            } else if (value instanceof String) {
                or.add(Restrictions.ilike(field, value.toString(), MatchMode.ANYWHERE));
            } else {
                or.add(Restrictions.like(field, value));
            }

            //or.add(Restrictions.ilike(String.valueOf(key), mapParam.get(key).toString(), MatchMode.ANYWHERE));
            criteria.add(or);
        }

    }
    logger.info("Start Row " + startRow);
    logger.info("Length Row " + lengthRow);
    //paging
    criteria.setFirstResult(startRow);
    criteria.setMaxResults(lengthRow);
    if (t instanceof ReferenceBase) {
        criteria.add(Restrictions.eq("deleted", 0));
        criteria.addOrder(Order.asc("id"));
    }

    try {
        logger.info(criteria.toString());
        rList = criteria.list();
    } catch (Exception e) {
        throw new Exception(e);
    }
    return rList;
}

From source file:org.jpos.gl.GLSession.java

License:Open Source License

/**
 * AccountDetail for date range//from w  w w .j  a  v a  2 s.  c  o  m
 * @param journal the journal.
 * @param acct the account.
 * @param start date (inclusive).
 * @param end date (inclusive).
 * @return Account detail for given period.
 * @throws GLException if user doesn't have READ permission on this jounral.
 */
public AccountDetail getAccountDetail(Journal journal, Account acct, Date start, Date end, short[] layers)
        throws HibernateException, GLException {
    checkPermission(GLPermission.READ);
    start = Util.floor(start);
    end = Util.ceil(end);

    Criteria crit = session.createCriteria(GLEntry.class);

    boolean hasChildren = false;
    if (acct instanceof CompositeAccount) {
        Disjunction dis = Restrictions.disjunction();
        for (Long l : getChildren(acct)) {
            hasChildren = true;
            dis.add(Restrictions.idEq(l));
        }
        if (hasChildren) {
            Criteria subCrit = crit.createCriteria(("account"));
            subCrit.add(dis);
        }
    }
    if (!hasChildren) {
        crit.add(Restrictions.eq("account", acct));
    }

    crit.add(Restrictions.in("layer", toShortArray(layers)));
    crit = crit.createCriteria("transaction").add(Restrictions.eq("journal", journal))
            .add(Restrictions.ge("postDate", start)).add(Restrictions.le("postDate", end));

    BigDecimal initialBalance[] = getBalances(journal, acct, start, false, layers, 0L);
    crit.addOrder(Order.asc("postDate"));
    crit.addOrder(Order.asc("timestamp"));
    crit.addOrder(Order.asc("id"));
    List entries = crit.list();
    // BigDecimal finalBalance = applyEntries (initialBalance[0], entries);

    return new AccountDetail(journal, acct, initialBalance[0], start, end, entries, layers);
}

From source file:org.jspresso.framework.application.backend.action.persistence.hibernate.QueryEntitiesAction.java

License:Open Source License

/**
 * Create a in list criterion potentially using disjunction to overcome the
 * size limitation of certain DBs in restriction (e.g. Oracle is 1000).
 *
 * @param entityIds/*from  ww  w  . ja  v a2 s.  co  m*/
 *     the list of entity ids.
 * @param chunkSize
 *     the size of disjunctions parts.
 * @return the criterion.
 */
public static Criterion createEntityIdsInCriterion(Collection<Serializable> entityIds, int chunkSize) {
    if (entityIds.size() < chunkSize) {
        return Restrictions.in(IEntity.ID, entityIds);
    }
    int i = 0;
    Disjunction splittedInlist = Restrictions.disjunction();
    Set<Serializable> currentEntityIds = new LinkedHashSet<>();
    boolean complete = false;
    for (Iterator<Serializable> ite = entityIds.iterator(); ite.hasNext(); i++) {
        currentEntityIds.add(ite.next());
        if (i % chunkSize == (chunkSize - 1)) {
            splittedInlist.add(Restrictions.in(IEntity.ID, currentEntityIds));
            currentEntityIds = new LinkedHashSet<>();
            complete = true;
        } else {
            complete = false;
        }
    }
    if (!complete) {
        splittedInlist.add(Restrictions.in(IEntity.ID, currentEntityIds));
    }
    return splittedInlist;
}