List of usage examples for org.hibernate.criterion Restrictions or
public static LogicalExpression or(Criterion lhs, Criterion rhs)
From source file:de.cosmocode.hibernate.CustomRestrictions.java
License:Apache License
/** * Apply a "not equal" constraint to the named property. * //from ww w.j a v a 2s .co m * <p> * Note: This implementation differs from {@link Restrictions#ne(String, Object)} * because it returns {@link CustomRestrictions#isNotEmpty(String)} * in case value is an empty string and returns an logical or expression * of {@link Restrictions#ne(String, Object)} and {@link Restrictions#isNull(String)}. * </p> * * @param propertyName the name of the property the constraint should be applied to * @param value the actual value the property should be not equals to * @return a new {@link Criterion} */ public static Criterion ne(String propertyName, String value) { if (StringUtils.isEmpty(value)) { return CustomRestrictions.isNotEmpty(propertyName); } else { return Restrictions.or(Restrictions.ne(propertyName, value), Restrictions.isNull(propertyName)); } }
From source file:de.cosmocode.hibernate.CustomRestrictions.java
License:Apache License
/** * Apply an "empty" constraint on the named property. * //from ww w .ja v a 2s. c om * <p> * See also {@link StringUtils#isEmpty(String)} * </p> * * @param propertyName the name of the property the constraint should be applied to * @return a new {@link Criterion} */ public static Criterion isEmpty(String propertyName) { return Restrictions.or(Restrictions.eq(propertyName, ""), Restrictions.isNull(propertyName)); }
From source file:de.cosmocode.hibernate.CustomRestrictions.java
License:Apache License
/** * Apply a "not ilike" constraint on the named property. * /*from ww w .j av a2 s . c o m*/ * <p> * This implementation handles empty values correctly. * </p> * * @param propertyName the name of the property the constraint should be applied to * @param value the actual value the property should be similiar to * @param matchMode the {@link MatchMode} being used * @return a new {@link Criterion} */ public static Criterion notIlike(String propertyName, String value, MatchMode matchMode) { if (StringUtils.isEmpty(value)) { return CustomRestrictions.isNotEmpty(propertyName); } else { return Restrictions.or(Restrictions.not(Restrictions.ilike(propertyName, value, matchMode)), CustomRestrictions.isEmpty(propertyName)); } }
From source file:de.decidr.model.commands.tenant.GetUsersOfTenantCommand.java
License:Apache License
@SuppressWarnings("unchecked") @Override//from w w w. j a v a2 s. co m public void transactionAllowed(TransactionStartedEvent evt) throws TransactionException { PaginatingCriteria c = new PaginatingCriteria(User.class, "u", evt.getSession()); String rootAlias = c.getAlias(); // Create criterion "user is a member of the tenant" DetachedCriteria memberRel = DetachedCriteria.forClass(UserIsMemberOfTenant.class, "memberRel"); memberRel.add(Property.forName("memberRel.user.id").eqProperty(rootAlias + ".id")) .add(Property.forName("memberRel.tenant.id").eq(getTenantId())); // Create criterion "user is the administrator of the tenant" DetachedCriteria adminRel = DetachedCriteria.forClass(Tenant.class, "adminTenant"); adminRel.add(Property.forName("adminTenant.id").eq(getTenantId())) .add(Property.forName("adminTenant.admin.id").eqProperty(rootAlias + ".id")); /* * Workaround for Hibernate issue HHH-993: Criteria subquery without * projection fails throwing NullPointerException. * * Additionally, Mysql doesn't seem to like aliases in EXISTS * subqueries, so we have to explicitly specify "*" */ Projection existsSubqueryProjection = Projections.sqlProjection("*", new String[0], new Type[0]); memberRel.setProjection(existsSubqueryProjection); adminRel.setProjection(existsSubqueryProjection); c.add(Restrictions.or(Subqueries.exists(memberRel), Subqueries.exists(adminRel))); // preload user profiles - no lazy loading desired c.createCriteria("userProfile", CriteriaSpecification.LEFT_JOIN); c.setResultTransformer(CriteriaSpecification.ROOT_ENTITY); if (paginator != null) { paginator.apply(c); } result = c.list(); }
From source file:de.decidr.model.commands.user.GetUserByLoginCommand.java
License:Apache License
@Override public void transactionAllowed(TransactionStartedEvent evt) throws TransactionException { passwordCorrect = false;/*from w w w . j a v a 2 s .c om*/ // find the existing user Criteria crit = evt.getSession().createCriteria(User.class, "u"); crit.createAlias("userProfile", "p", CriteriaSpecification.LEFT_JOIN); // the DecidR username criteria do not allow non-alphanumeric characters // in usernames, so the case user1.username = user2.email should not // occur. Otherwise, uniqueResult() will throw a runtime exception. crit.add(Restrictions.or(Restrictions.eq("u.email", emailOrUsername), Restrictions.eq("p.username", emailOrUsername))); User existingUser = (User) crit.uniqueResult(); if (existingUser == null) { // user account not found throw new EntityNotFoundException(User.class); } String hash = Password.getHash(passwordPlaintext, existingUser.getUserProfile().getPasswordSalt()); // is the password correct? passwordCorrect = hash.equals(existingUser.getUserProfile().getPasswordHash()); user = existingUser; // log the login to the database Login thisLogin = new Login(); thisLogin.setLoginDate(DecidrGlobals.getTime().getTime()); thisLogin.setSuccess(passwordCorrect); thisLogin.setUser(existingUser); evt.getSession().save(thisLogin); }
From source file:de.escidoc.core.aa.business.filter.RoleGrantFilter.java
License:Open Source License
/** * Convert the CQL filter into a Hibernate query. * * @return Hibernate query representing this filter * @throws InvalidSearchQueryException thrown if the given search query could not be translated into a SQL query *///from w w w . ja v a 2 s . c o m @Override public DetachedCriteria toSql() throws InvalidSearchQueryException { final DetachedCriteria result = super.toSql(); // users Criterion userCriterion = null; if (this.userIds != null && !userIds.isEmpty()) { userCriterion = getInRestrictions(this.userIds, "userId"); } // groups Criterion groupCriterion = null; if (this.groupIds != null && !groupIds.isEmpty()) { groupCriterion = getInRestrictions(this.groupIds, "groupId"); } // concatenate users and groups with OR if (userCriterion != null || groupCriterion != null) { if (userCriterion == null) { result.add(groupCriterion); } else if (groupCriterion == null) { result.add(userCriterion); } else { result.add(Restrictions.or(userCriterion, groupCriterion)); } } return result; }
From source file:de.escidoc.core.aa.business.persistence.hibernate.HibernateEscidocRoleDao.java
License:Open Source License
/** * See Interface for functional description. * * @see EscidocRoleDaoInterface #roleExists(java.lang.String) *//*from ww w . j av a2s . co m*/ @Override public boolean roleExists(final String identifier) throws SqlDatabaseSystemException { boolean result = false; if (identifier != null) { try { final DetachedCriteria criteria = DetachedCriteria.forClass(EscidocRole.class).add(Restrictions .or(Restrictions.eq("id", identifier), Restrictions.eq("roleName", identifier))); result = !getHibernateTemplate().findByCriteria(criteria).isEmpty(); } catch (final DataAccessException e1) { throw new SqlDatabaseSystemException(e1); } catch (final IllegalStateException e1) { throw new SqlDatabaseSystemException(e1); } catch (final HibernateException e) { //noinspection ThrowableResultOfMethodCallIgnored throw new SqlDatabaseSystemException(convertHibernateAccessException(e)); // Ignore FindBugs } } return result; }
From source file:de.escidoc.core.aa.business.persistence.hibernate.HibernateUserAccountDao.java
License:Open Source License
/** * See Interface for functional description. * * @see UserAccountDaoInterface #userAccountExists(java.lang.String) */// w w w .j av a2 s .com @Override public boolean userAccountExists(final String identityInfo) throws SqlDatabaseSystemException { boolean result = false; if (identityInfo != null) { try { // try identification by id or login name final DetachedCriteria criteria = DetachedCriteria.forClass(UserAccount.class).add(Restrictions .or(Restrictions.eq("id", identityInfo), Restrictions.eq("loginname", identityInfo))); result = !getHibernateTemplate().findByCriteria(criteria).isEmpty(); if (!result) { // try identification by handle result = !getHibernateTemplate() .find(QUERY_RETRIEVE_USER_ACCOUNT_BY_HANDLE, identityInfo, System.currentTimeMillis()) .isEmpty(); } } catch (final DataAccessException e) { throw new SqlDatabaseSystemException(e); } catch (final IllegalStateException e) { throw new SqlDatabaseSystemException(e); } catch (final HibernateException e) { //noinspection ThrowableResultOfMethodCallIgnored throw new SqlDatabaseSystemException(convertHibernateAccessException(e)); // Ignore FindBugs } } return result; }
From source file:de.escidoc.core.aa.business.persistence.hibernate.HibernateUserAccountDao.java
License:Open Source License
/** * See Interface for functional description. * * @see UserAccountDaoInterface #retrieveGrants(java.util.Map, int, int, String, ListSorting) */// w w w . ja v a 2 s. c o m @Override public List<RoleGrant> retrieveGrants(final Map<String, HashSet<String>> criterias, final String orderBy, final ListSorting sorting) throws SqlDatabaseSystemException { final DetachedCriteria detachedCriteria = DetachedCriteria.forClass(RoleGrant.class, "roleGrant"); final Map<String, Object> clonedCriterias = new HashMap<String, Object>(criterias); // users final Set<String> userIds = mergeSets((Set<String>) clonedCriterias.remove(Constants.FILTER_USER), (Set<String>) clonedCriterias.remove(Constants.FILTER_PATH_USER_ID)); Criterion userCriterion = null; if (userIds != null && !userIds.isEmpty()) { userCriterion = getInRestrictions(userIds, "userId"); } // groups final Set<String> groupIds = mergeSets((Set<String>) clonedCriterias.remove(Constants.FILTER_GROUP), (Set<String>) clonedCriterias.remove(Constants.FILTER_PATH_GROUP_ID)); Criterion groupCriterion = null; if (groupIds != null && !groupIds.isEmpty()) { groupCriterion = getInRestrictions(groupIds, "groupId"); } // concatenate users and groups with OR if (userCriterion != null || groupCriterion != null) { if (userCriterion == null) { detachedCriteria.add(groupCriterion); } else if (groupCriterion == null) { detachedCriteria.add(userCriterion); } else { detachedCriteria.add(Restrictions.or(userCriterion, groupCriterion)); } } // roles final Set<String> roleIds = mergeSets((Set<String>) clonedCriterias.remove(Constants.FILTER_ROLE), (Set<String>) clonedCriterias.remove(Constants.FILTER_PATH_ROLE_ID)); if (roleIds != null && !roleIds.isEmpty()) { detachedCriteria.add(getInRestrictions(roleIds, "roleId")); } // assigned-on final Set<String> objectIds = mergeSets((Set<String>) clonedCriterias.remove(Constants.FILTER_ASSIGNED_ON), (Set<String>) clonedCriterias.remove(Constants.FILTER_PATH_ASSIGNED_ON_ID)); if (objectIds != null && !objectIds.isEmpty()) { detachedCriteria.add(getInRestrictions(objectIds, "objectId")); } // created-by final Set<String> creatorIds = mergeSets((Set<String>) clonedCriterias.remove(Constants.FILTER_CREATED_BY), (Set<String>) clonedCriterias.remove(Constants.FILTER_PATH_CREATED_BY_ID)); if (creatorIds != null && !creatorIds.isEmpty()) { detachedCriteria.add(getInRestrictions(creatorIds, "creatorId")); } // revoked-by final Set<String> revokerIds = mergeSets((Set<String>) clonedCriterias.remove(Constants.FILTER_REVOKED_BY), (Set<String>) clonedCriterias.remove(Constants.FILTER_PATH_REVOKED_BY_ID)); if (revokerIds != null && !revokerIds.isEmpty()) { detachedCriteria.add(getInRestrictions(revokerIds, "revokerId")); } if (orderBy != null) { if (sorting == ListSorting.ASCENDING) { detachedCriteria.addOrder(Order.asc(grantPropertiesNamesMap.get(orderBy))); } else if (sorting == ListSorting.DESCENDING) { detachedCriteria.addOrder(Order.desc(grantPropertiesNamesMap.get(orderBy))); } } if (clonedCriterias.isEmpty()) { final List<RoleGrant> result; try { result = getHibernateTemplate().findByCriteria(detachedCriteria); } catch (final DataAccessException e) { throw new SqlDatabaseSystemException(e); } return result; } else { // unsupported filter criteria has been found, therefore the result // list must be empty. return new ArrayList<RoleGrant>(0); } }
From source file:de.escidoc.core.aa.business.persistence.hibernate.HibernateUserAccountDao.java
License:Open Source License
/** * See Interface for functional description. * * @param attributes set of key/value pairs * @see UserAccountDaoInterface #retrieveAttributes(java.lang.String) *//*from w w w . j a va 2s . c o m*/ @Override public List<UserAttribute> retrieveAttributes(final Set<HashMap<String, String>> attributes) throws SqlDatabaseSystemException { if (attributes == null) { throw new SqlDatabaseSystemException("attributes may not be null"); } final DetachedCriteria detachedCriteria = DetachedCriteria.forClass(UserAttribute.class, "userAttribute"); Criterion criterion = null; for (final Map<String, String> attribute : attributes) { for (final Entry<String, String> entry : attribute.entrySet()) { if (criterion == null) { criterion = Restrictions.and(Restrictions.eq("name", entry.getKey()), Restrictions.eq("value", entry.getValue())); } else { final Criterion criterion1 = Restrictions.and(Restrictions.eq("name", entry.getKey()), Restrictions.eq("value", entry.getValue())); criterion = Restrictions.or(criterion, criterion1); } } } detachedCriteria.add(criterion); final List<UserAttribute> result; try { result = getHibernateTemplate().findByCriteria(detachedCriteria); } catch (final DataAccessException e) { throw new SqlDatabaseSystemException(e); } return result; }