Example usage for org.hibernate.criterion Restrictions conjunction

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

Introduction

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

Prototype

public static Conjunction conjunction() 

Source Link

Document

Group expressions together in a single conjunction (A and B and C...).

Usage

From source file:org.hsqldb.hibernate.geomajas.layer.hibernate.CriteriaVisitor.java

License:Open Source License

/** {@inheritDoc} */
public Object visit(ExcludeFilter filter, Object userData) {
    return Restrictions.not(Restrictions.conjunction());
}

From source file:org.hsqldb.hibernate.geomajas.layer.hibernate.CriteriaVisitor.java

License:Open Source License

/** {@inheritDoc} */
public Object visit(IncludeFilter filter, Object userData) {
    return Restrictions.conjunction();
}

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/*w ww  .jav  a  2s. co  m*/
 * @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  av a2  s  .  c  o  m
 * @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.infoscoop.dao.OAuthConsumerDAO.java

License:Open Source License

public OAuthConsumerProp getConsumer(String gadgetUrl, String serviceName) {
    if (gadgetUrl == null || serviceName == null) {
        throw new RuntimeException("gadgetUrl and serviceName must be set.");
    }/*  w  w  w  . j a  v a  2s.  c om*/

    Iterator results = super.getHibernateTemplate()
            .findByCriteria(
                    DetachedCriteria.forClass(OAuthConsumerProp.class, "ocp")
                            .createAlias("OAuthGadgetUrl", "ogu", CriteriaSpecification.LEFT_JOIN)
                            .add(Restrictions.conjunction().add(Restrictions.eq("ocp.ServiceName", serviceName))
                                    .add(Restrictions.eq("ogu.GadgetUrlKey", Crypt.getHash(gadgetUrl)))))
            .iterator();

    if (results.hasNext()) {
        return (OAuthConsumerProp) results.next();
    }

    return null;
}

From source file:org.infoscoop.dao.OAuthConsumerDAO.java

License:Open Source License

public Boolean validateConsumerByIdAndServiceAndURL(String id, String serviceName, String gadgetUrl) {
    // Refactoring: create hibernate object (mapping? criteria? and o)
    Iterator results = super.getHibernateTemplate()
            .findByCriteria(DetachedCriteria.forClass(OAuthConsumerProp.class, "ocp")
                    .createAlias("OAuthGadgetUrl", "ogu", CriteriaSpecification.LEFT_JOIN)
                    .add(Restrictions.conjunction().add(Restrictions.ne("ocp.Id", id))
                            .add(Restrictions.eq("ocp.ServiceName", serviceName))
                            .add(Restrictions.eq("ogu.GadgetUrlKey", Crypt.getHash(gadgetUrl)))))
            .iterator();/*from   ww w.  ja v a 2  s  . co  m*/

    if (results.hasNext()) {
        // if same contents are had, database is not updated.
        return true;
    }

    return false;
}

From source file:org.infoscoop.dao.OAuthTokenDAO.java

License:Open Source License

@SuppressWarnings("unchecked")
public OAuthToken getAccessToken(String uid, String gadgetUrl, String serviceName) {
    if (uid == null || gadgetUrl == null || serviceName == null) {
        throw new RuntimeException("uid, gadgetUrl and serviceName must be set.");
    }/*from ww  w .j  a  va2s . co  m*/
    Iterator results = super.getHibernateTemplate()
            .findByCriteria(DetachedCriteria.forClass(OAuthConsumerProp.class, "ocp")
                    .createAlias("OAuthGadgetUrl", "ogu", CriteriaSpecification.LEFT_JOIN)
                    .createAlias("OAuthToken", "ot", CriteriaSpecification.LEFT_JOIN)
                    .add(Restrictions.conjunction().add(Restrictions.eq("ot.Id.Uid", uid))
                            .add(Restrictions.eq("ocp.ServiceName", serviceName))
                            .add(Restrictions.eq("ogu.GadgetUrlKey", Crypt.getHash(gadgetUrl)))))
            .iterator();

    if (results.hasNext()) {
        OAuthConsumerProp o = (OAuthConsumerProp) results.next();
        Set<OAuthToken> s = o.getOAuthToken();
        Iterator i = s.iterator();
        if (i.hasNext())
            return (OAuthToken) i.next();
    }
    return null;
}

From source file:org.infoscoop.dao.OAuthTokenDAO.java

License:Open Source License

@SuppressWarnings("unchecked")
public List<OAuthToken> getAccessTokens(String uid, String serviceName) {
    if (uid == null || serviceName == null) {
        throw new RuntimeException("uid and serviceName must be set.");
    }/*from  w  ww  .j  ava  2 s  .co  m*/
    Iterator<OAuthConsumerProp> results = super.getHibernateTemplate()
            .findByCriteria(DetachedCriteria.forClass(OAuthConsumerProp.class, "ocp")
                    .createAlias("OAuthGadgetUrl", "ogu", CriteriaSpecification.LEFT_JOIN)
                    .createAlias("OAuthToken", "ot", CriteriaSpecification.LEFT_JOIN)
                    .add(Restrictions.conjunction().add(Restrictions.eq("ot.Id.Uid", uid))
                            .add(Restrictions.eq("ocp.ServiceName", serviceName))))
            .iterator();

    if (results.hasNext()) {
        OAuthConsumerProp o = (OAuthConsumerProp) results.next();
        List l = new ArrayList();
        l.addAll(o.getOAuthToken());
        return l;
    }
    return null;
}

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);
    }/*ww w. j  a  v  a  2 s . c o  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.jspresso.framework.model.persistence.hibernate.criterion.DefaultCriteriaFactory.java

License:Open Source License

/**
 * Complete criteria with translations.//w  w w.ja va  2 s . com
 *
 * @param currentCriteria
 *     the current criteria
 * @param translationsPath
 *     the translations path
 * @param translationsAlias
 *     the translations alias
 * @param property
 *     the property
 * @param propertyDescriptor
 *     the property descriptor
 * @param prefixedProperty
 *     the prefixed property
 * @param locale
 *     the locale
 * @param componentDescriptor
 *     the component descriptor
 * @param queryComponent
 *     the query component
 * @param context
 *     the context
 */
@SuppressWarnings("unchecked")
protected void completeCriteriaWithTranslations(DetachedCriteria currentCriteria, String translationsPath,
        String translationsAlias, Map.Entry<String, Object> property, IPropertyDescriptor propertyDescriptor,
        String prefixedProperty, Locale locale, IComponentDescriptor<?> componentDescriptor,
        IQueryComponent queryComponent, Map<String, Object> context) {
    if (propertyDescriptor instanceof IStringPropertyDescriptor
            && ((IStringPropertyDescriptor) propertyDescriptor).isTranslatable()) {
        String nlsOrRawValue = null;
        String nlsValue = (String) property.getValue();
        String barePropertyName = property.getKey();
        if (property.getKey().endsWith(IComponentDescriptor.NLS_SUFFIX)) {
            barePropertyName = barePropertyName.substring(0,
                    barePropertyName.length() - IComponentDescriptor.NLS_SUFFIX.length());
        } else {
            nlsOrRawValue = nlsValue;
        }
        if (nlsValue != null) {
            Junction translationRestriction = Restrictions.conjunction();
            translationRestriction.add(createStringRestriction(
                    ((ICollectionPropertyDescriptor<IPropertyTranslation>) componentDescriptor
                            .getPropertyDescriptor(translationsPath)).getCollectionDescriptor()
                                    .getElementDescriptor()
                                    .getPropertyDescriptor(IPropertyTranslation.TRANSLATED_VALUE),
                    translationsAlias + "." + IPropertyTranslation.TRANSLATED_VALUE, nlsValue,
                    componentDescriptor, queryComponent, context));
            String languagePath = translationsAlias + "." + IPropertyTranslation.LANGUAGE;
            translationRestriction.add(Restrictions.eq(languagePath, locale.getLanguage()));
            translationRestriction.add(Restrictions
                    .eq(translationsAlias + "." + IPropertyTranslation.PROPERTY_NAME, barePropertyName));

            Junction disjunction = Restrictions.disjunction();
            disjunction.add(translationRestriction);
            if (nlsOrRawValue != null) {
                Junction rawValueRestriction = Restrictions.conjunction();
                rawValueRestriction.add(Restrictions.disjunction().add(Restrictions.isNull(languagePath))
                        .add(Restrictions.ne(languagePath, locale.getLanguage())));
                String rawPropertyName = barePropertyName + IComponentDescriptor.RAW_SUFFIX;
                rawValueRestriction
                        .add(createStringRestriction(componentDescriptor.getPropertyDescriptor(rawPropertyName),
                                rawPropertyName, nlsOrRawValue, componentDescriptor, queryComponent, context));
                disjunction.add(rawValueRestriction);
            }
            currentCriteria.add(disjunction);
        }
    } else {
        completeCriteria(currentCriteria, createStringRestriction(propertyDescriptor, prefixedProperty,
                (String) property.getValue(), componentDescriptor, queryComponent, context));
    }
}