Example usage for org.hibernate.criterion Restrictions like

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

Introduction

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

Prototype

public static SimpleExpression like(String propertyName, Object value) 

Source Link

Document

Apply a "like" constraint to the named property

Usage

From source file:com.ephesoft.dcma.da.dao.hibernate.BatchInstanceDaoImpl.java

License:Open Source License

/**
 * An API to fetch all the batch instances by status list. Parameter firstResult set a limit upon the number of objects to be
 * retrieved. Parameter maxResults set the first result to be retrieved. Parameter orderList set the sort property and order of
 * that property. If orderList parameter is null or empty then this parameter is avoided.
 * //from   w w w.  j  av a 2s.com
 * @param statusList List<BatchInstanceStatus> status list of batch instance status.
 * @param firstResult the first result to retrieve, numbered from <tt>0</tt>
 * @param maxResults maxResults the maximum number of results
 * @param orderList List<Order> orderList set the sort property and order of that property. If orderList parameter is null or empty
 *            then this parameter is avoided.
 * @param filterClauseList List<BatchInstanceFilter> this will add the where clause to the criteria query based on the property
 *            name and value. If filterClauseList parameter is null or empty then this parameter is avoided.
 * @param batchPriorities List<BatchPriority> this will add the where clause to the criteria query based on the priority list
 *            selected. If batchPriorities parameter is null or empty then this parameter is avoided.
 * @param userName Current user name.
 * @param userRoles currentUserRoles
 * @param EphesoftUser current ephesoft-user
 * @param criteria EphesoftCriteria
 * @param searchString the searchString on which batch instances have to be fetched
 * @return List<BatchInstance> return the batch instance list.
 */
public List<BatchInstance> getBatchInstances(List<BatchInstanceStatus> statusList, final int firstResult,
        final int maxResults, final List<Order> orderList, final List<BatchInstanceFilter> filterClauseList,
        final List<BatchPriority> batchPriorities, String userName, final Set<String> userRoles,
        EphesoftUser ephesoftUser, final EphesoftCriteria criteria, final String searchString) {
    EphesoftCriteria criteriaLocal = null;
    if (criteria == null) {
        criteriaLocal = criteria();
    } else {
        criteriaLocal = criteria;
    }

    // For adding identifier as an criteria for result
    if (null != searchString && !searchString.isEmpty()) {
        String searchStringLocal = searchString.replaceAll("%", "\\\\%");
        Criterion nameLikeCriteria = Restrictions.like(BATCH_NAME, "%" + searchStringLocal + "%");
        Criterion idLikeCriteria = Restrictions.like(BATCH_INSTANCE_IDENTIFIER, "%" + searchStringLocal + "%");

        LogicalExpression searchCriteria = Restrictions.or(nameLikeCriteria, idLikeCriteria);
        criteriaLocal.add(searchCriteria);
    }

    if (null != statusList) {
        criteriaLocal.add(Restrictions.in(STATUS, statusList));
        // criteria.add(Restrictions.or(Restrictions.isNull(CURRENT_USER), Restrictions.eq(CURRENT_USER, userName)));
    }

    if (null != batchPriorities && !(batchPriorities.isEmpty())) {
        Disjunction disjunction = Restrictions.disjunction();
        for (BatchPriority batchPriority : batchPriorities) {
            if (null != batchPriority) {
                Integer lowValue = batchPriority.getLowerLimit();
                Integer upperValue = batchPriority.getUpperLimit();
                disjunction.add(Restrictions.between(PRIORITY, lowValue, upperValue));
            } else {
                disjunction = Restrictions.disjunction();
                break;
            }
        }
        criteriaLocal.add(disjunction);

    }

    List<BatchInstance> batchInstaceList = new ArrayList<BatchInstance>();
    BatchInstanceFilter[] filters = null;
    Order[] orders = null;
    switch (ephesoftUser) {
    default:
        Set<String> batchClassIndentifiers = batchClassGroupsDao.getBatchClassIdentifierForUserRoles(userRoles);
        Set<String> batchInstanceIndentifiers = batchInstanceGroupsDao
                .getBatchInstanceIdentifierForUserRoles(userRoles);
        if ((null != batchClassIndentifiers && batchClassIndentifiers.size() > 0)
                || (null != batchInstanceIndentifiers && batchInstanceIndentifiers.size() > 0)) {
            if (filterClauseList != null) {
                filters = filterClauseList.toArray(new BatchInstanceFilter[filterClauseList.size()]);
            }
            if (orderList != null) {
                orders = orderList.toArray(new Order[orderList.size()]);
            }
            if (null != batchClassIndentifiers && batchClassIndentifiers.size() > 0
                    && null != batchInstanceIndentifiers && batchInstanceIndentifiers.size() > 0) {
                final Disjunction disjunction = Restrictions.disjunction();
                if (null != batchClassIndentifiers && batchClassIndentifiers.size() > 0) {
                    criteriaLocal.createAlias(BATCH_CLASS, BATCH_CLASS);
                    disjunction.add(Restrictions.in(BATCH_CLASS_IDENTIFIER, batchClassIndentifiers));
                }
                if (null != batchInstanceIndentifiers && batchInstanceIndentifiers.size() > 0) {
                    disjunction.add(Restrictions.in(BATCH_INSTANCE_IDENTIFIER, batchInstanceIndentifiers));
                }
                criteriaLocal.add(disjunction);
            } else if (null != batchClassIndentifiers && batchClassIndentifiers.size() > 0) {
                criteriaLocal.createAlias(BATCH_CLASS, BATCH_CLASS);
                criteriaLocal.add(Restrictions.in(BATCH_CLASS_IDENTIFIER, batchClassIndentifiers));
            } else if (null != batchInstanceIndentifiers && batchInstanceIndentifiers.size() > 0) {
                criteriaLocal.add(Restrictions.in(BATCH_INSTANCE_IDENTIFIER, batchInstanceIndentifiers));
            }
            batchInstaceList = find(criteriaLocal, firstResult, maxResults, filters, orders);
        }
        break;
    }
    return batchInstaceList;
}

From source file:com.eucalyptus.blockstorage.async.SnapshotTransferCleaner.java

License:Open Source License

private void deleteExpiredUploads() {
    try (TransactionResource snapTran = Entities.transactionFor(SnapshotUploadInfo.class)) {
        Criterion criterion = Restrictions.and(
                Restrictions.or(Restrictions.like("state", SnapshotUploadState.cleaned),
                        Restrictions.like("state", SnapshotUploadState.uploaded)),
                Restrictions.le("purgeTime", System.currentTimeMillis()));
        List<SnapshotUploadInfo> snapshotUploadInfoList = Entities.query(new SnapshotUploadInfo(),
                Boolean.FALSE, criterion, Collections.EMPTY_MAP);
        for (SnapshotUploadInfo snapUploadInfo : snapshotUploadInfoList) {
            LOG.debug("Deleting expired entity from DB " + snapUploadInfo);
            Map<String, String> parameters = Maps.newHashMap();
            parameters.put("snapshotId", snapUploadInfo.getSnapshotId());
            parameters.put("bucketName", snapUploadInfo.getBucketName());
            parameters.put("keyName", snapUploadInfo.getKeyName());
            if (snapUploadInfo.getUploadId() != null) {
                parameters.put("uploadId", snapUploadInfo.getUploadId());
                Entities.deleteAllMatching(SnapshotPart.class,
                        "WHERE snapshot_id = :snapshotId AND bucket_name = :bucketName AND key_name = :keyName AND upload_id = :uploadId",
                        parameters);//w w  w.  j  a  va  2  s.  c  o  m
            } else {
                Entities.deleteAllMatching(SnapshotPart.class,
                        "WHERE snapshot_id = :snapshotId AND bucket_name = :bucketName AND key_name = :keyName",
                        parameters);
            }
            Entities.delete(snapUploadInfo);
        }
        snapTran.commit();
    } catch (Exception e) {
        LOG.debug("Error deleting expired snapshot upload info entities" + e);
    }
}

From source file:com.eucalyptus.blockstorage.util.BlockStorageUtil.java

License:Open Source License

public static final Criterion getFailedCriterion() {
    return Restrictions.and(Restrictions.like("status", StorageProperties.Status.failed.toString()),
            Restrictions.isNull("deletionTime"));
}

From source file:com.eucalyptus.cloudwatch.common.internal.domain.alarms.AlarmManager.java

License:Open Source License

public static List<AlarmEntity> describeAlarms(@Nullable final String accountId,
        @Nullable final String actionPrefix, @Nullable final String alarmNamePrefix,
        @Nullable final Collection<String> alarmNames, @Nullable final Integer maxRecords,
        @Nullable final StateValue stateValue, @Nullable final String nextToken,
        final Predicate<? super CloudWatchMetadata.AlarmMetadata> filter) throws InvalidTokenException {
    final List<AlarmEntity> results = Lists.newArrayList();
    try (final TransactionResource db = Entities.transactionFor(AlarmEntity.class)) {
        boolean first = true;
        String token = nextToken;
        while (token != null || first) {
            first = false;//from   w w  w. j  a  v a2 s.c  om
            final Date nextTokenCreatedTime = NextTokenUtils.getNextTokenCreatedTime(token, AlarmEntity.class);
            final Criteria criteria = Entities.createCriteria(AlarmEntity.class);
            if (accountId != null) {
                criteria.add(Restrictions.eq("accountId", accountId));
            }
            if (actionPrefix != null) {
                final Junction actionsOf = Restrictions.disjunction();
                for (int i = 1; i <= AlarmEntity.MAX_OK_ACTIONS_NUM; i++) {
                    actionsOf.add(Restrictions.like("okAction" + i, actionPrefix + "%")); // May need Restrictions.ilike for case insensitive
                }
                for (int i = 1; i <= AlarmEntity.MAX_ALARM_ACTIONS_NUM; i++) {
                    actionsOf.add(Restrictions.like("alarmAction" + i, actionPrefix + "%")); // May need Restrictions.ilike for case insensitive
                }
                for (int i = 1; i <= AlarmEntity.MAX_INSUFFICIENT_DATA_ACTIONS_NUM; i++) {
                    actionsOf.add(Restrictions.like("insufficientDataAction" + i, actionPrefix + "%")); // May need Restrictions.ilike for case insensitive
                }
                criteria.add(actionsOf);
            }
            if (alarmNamePrefix != null) {
                criteria.add(Restrictions.like("alarmName", alarmNamePrefix + "%"));
            }
            if (alarmNames != null && !alarmNames.isEmpty()) {
                criteria.add(Restrictions.in("alarmName", alarmNames));
            }
            if (stateValue != null) {
                criteria.add(Restrictions.eq("stateValue", stateValue));
            }
            NextTokenUtils.addNextTokenConstraints(maxRecords == null ? null : maxRecords - results.size(),
                    token, nextTokenCreatedTime, criteria);
            final List<AlarmEntity> alarmEntities = (List<AlarmEntity>) criteria.list();
            Iterables.addAll(results, Iterables.filter(alarmEntities, filter));
            token = maxRecords == null || (maxRecords != null
                    && (results.size() >= maxRecords || alarmEntities.size() < maxRecords)) ? null
                            : alarmEntities.get(alarmEntities.size() - 1).getNaturalId();
        }
        db.commit();
    }
    return results;
}

From source file:com.eucalyptus.cloudwatch.domain.alarms.AlarmManager.java

License:Open Source License

public static List<AlarmEntity> describeAlarms(@Nullable final String accountId,
        @Nullable final String actionPrefix, @Nullable final String alarmNamePrefix,
        @Nullable final Collection<String> alarmNames, @Nullable final Integer maxRecords,
        @Nullable final StateValue stateValue, @Nullable final String nextToken,
        final Predicate<CloudWatchMetadata.AlarmMetadata> filter) throws CloudWatchException {
    final List<AlarmEntity> results = Lists.newArrayList();
    final EntityTransaction db = Entities.get(AlarmEntity.class);
    try {//from   w w w.ja va 2  s  .co m
        boolean first = true;
        String token = nextToken;
        while (token != null || first) {
            first = false;
            final Date nextTokenCreatedTime = NextTokenUtils.getNextTokenCreatedTime(token, AlarmEntity.class,
                    true);
            final Criteria criteria = Entities.createCriteria(AlarmEntity.class);
            if (accountId != null) {
                criteria.add(Restrictions.eq("accountId", accountId));
            }
            if (actionPrefix != null) {
                final Junction actionsOf = Restrictions.disjunction();
                for (int i = 1; i <= AlarmEntity.MAX_OK_ACTIONS_NUM; i++) {
                    actionsOf.add(Restrictions.like("okAction" + i, actionPrefix + "%")); // May need Restrictions.ilike for case insensitive
                }
                for (int i = 1; i <= AlarmEntity.MAX_ALARM_ACTIONS_NUM; i++) {
                    actionsOf.add(Restrictions.like("alarmAction" + i, actionPrefix + "%")); // May need Restrictions.ilike for case insensitive
                }
                for (int i = 1; i <= AlarmEntity.MAX_INSUFFICIENT_DATA_ACTIONS_NUM; i++) {
                    actionsOf.add(Restrictions.like("insufficientDataAction" + i, actionPrefix + "%")); // May need Restrictions.ilike for case insensitive
                }
                criteria.add(actionsOf);
            }
            if (alarmNamePrefix != null) {
                criteria.add(Restrictions.like("alarmName", alarmNamePrefix + "%"));
            }
            if (alarmNames != null && !alarmNames.isEmpty()) {
                criteria.add(Restrictions.in("alarmName", alarmNames));
            }
            if (stateValue != null) {
                criteria.add(Restrictions.eq("stateValue", stateValue));
            }
            NextTokenUtils.addNextTokenConstraints(maxRecords == null ? null : maxRecords - results.size(),
                    token, nextTokenCreatedTime, criteria);
            final List<AlarmEntity> alarmEntities = (List<AlarmEntity>) criteria.list();
            Iterables.addAll(results, Iterables.filter(alarmEntities, filter));
            token = maxRecords == null || (maxRecords != null
                    && (results.size() >= maxRecords || alarmEntities.size() < maxRecords)) ? null
                            : alarmEntities.get(alarmEntities.size() - 1).getNaturalId();
        }
        db.commit();
    } catch (RuntimeException ex) {
        Logs.extreme().error(ex, ex);
        throw ex;
    } finally {
        if (db.isActive())
            db.rollback();
    }
    return results;
}

From source file:com.eucalyptus.compute.common.internal.tags.FilterSupport.java

License:Open Source License

/**
 * Construct a criterion from a filter pattern.
 *
 * A Pattern is constructed from the given filter, as per AWS:
 *
 *  Filters support the following wildcards:
 *
 *    *: Matches zero or more characters
 *    ?: Matches exactly one character/*w w  w . j  a  v  a  2s.  c  o  m*/
 *
 *   Your search can include the literal values of the wildcard characters; you just need to escape
 *   them with a backslash before the character. For example, a value of \*amazon\?\\ searches for
 *   the literal string *amazon?\.
 *
 * Wildcards are translated for use with 'like':
 *
 *   % : Matches zero or more characters
 *   _: Matches exactly one character
 *
 * In both cases wildcards can be escaped (to allow literal values) with a backslash (\).
 *
 * Translation of wildcards for direct DB filtering must support literal values from each grammar.
 */
private Criterion buildRestriction(final String property, final Object persistentValue) {
    final Object valueObject;
    if (persistentValue instanceof String) {
        final String value = persistentValue.toString();
        final StringBuilder likeValueBuilder = new StringBuilder();
        translateWildcards(value, likeValueBuilder, "_", "%", SyntaxEscape.Like);
        final String likeValue = likeValueBuilder.toString();

        if (!value.equals(likeValue)) { // even if no regex, may contain \ escapes that must be removed
            return Restrictions.like(property, likeValue);
        }

        valueObject = persistentValue;
    } else {
        valueObject = persistentValue;
    }

    if (persistentValue instanceof Collection) {
        if (((Collection) persistentValue).isEmpty()) {
            return Restrictions.not(Restrictions.conjunction()); // always false
        } else {
            return Restrictions.in(property, (Collection) persistentValue);
        }
    } else {
        return Restrictions.eq(property, valueObject);
    }
}

From source file:com.eucalyptus.compute.common.internal.tags.Tags.java

License:Open Source License

/**
 * Count tags matching the given example and criteria.
 *
 * <p>The count will not include reserved tags.</p>
 *
 * @param example The tag example//ww w  . j a  v a 2s.  c  om
 * @return The matching tag count.
 */
public static long count(final Tag example) {
    final EntityTransaction transaction = Entities.get(example);
    try {
        final Junction reservedTagKey = Restrictions.disjunction();
        reservedTagKey.add(Restrictions.like("displayName", "aws:%"));
        reservedTagKey.add(Restrictions.like("displayName", "euca:%"));
        return Entities.count(example, Restrictions.not(reservedTagKey),
                Collections.<String, String>emptyMap());
    } finally {
        transaction.rollback();
    }
}

From source file:com.evolveum.midpoint.repo.sql.helpers.LookupTableHelper.java

License:Apache License

private Criteria setupLookupTableRowsQuery(Session session, RelationalValueSearchQuery queryDef, String oid) {
    Criteria criteria = session.createCriteria(RLookupTableRow.class);
    criteria.add(Restrictions.eq("ownerOid", oid));

    if (queryDef != null && queryDef.getColumn() != null && queryDef.getSearchType() != null
            && StringUtils.isNotEmpty(queryDef.getSearchValue())) {

        String param = queryDef.getColumn().getLocalPart();
        String value = queryDef.getSearchValue();
        if (LookupTableRowType.F_LABEL.equals(queryDef.getColumn())) {
            param = "label.norm";

            PolyString poly = new PolyString(value);
            poly.recompute(new PrismDefaultPolyStringNormalizer());
            value = poly.getNorm();/*from  w ww.j  av a2 s  . c  o  m*/
        }
        switch (queryDef.getSearchType()) {
        case EXACT:
            criteria.add(Restrictions.eq(param, value));
            break;
        case STARTS_WITH:
            criteria.add(Restrictions.like(param, value + "%"));
            break;
        case SUBSTRING:
            criteria.add(Restrictions.like(param, "%" + value + "%"));
        }
    }

    return criteria;
}

From source file:com.evolveum.midpoint.repo.sql.QueryInterpreterTest.java

License:Apache License

@Test
public void queryUserSubstringFullName() throws Exception {
    Session session = open();//from www. j a va  2s.c o m

    try {
        Criteria main = session.createCriteria(RUser.class, "u");
        ProjectionList projections = Projections.projectionList();
        addFullObjectProjectionList("u", projections, false);
        main.setProjection(projections);

        main.add(Restrictions.like("fullName.norm", "%cpt jack sparrow%").ignoreCase());
        String expected = HibernateToSqlTranslator.toSql(main);

        String real = getInterpretedQuery(session, UserType.class,
                new File(TEST_DIR, "query-user-substring-fullName.xml"));

        LOGGER.info("exp. query>\n{}\nreal query>\n{}", new Object[] { expected, real });
        AssertJUnit.assertEquals(expected, real);
    } finally {
        close(session);
    }
}

From source file:com.evolveum.midpoint.repo.sql.QueryInterpreterTest.java

License:Apache License

@Test
public void test330queryUserSubstringName() throws Exception {
    Session session = open();//from  w ww.ja  v  a  2s  . com

    try {
        Criteria main = session.createCriteria(RObject.class, "o");
        ProjectionList projections = Projections.projectionList();
        addFullObjectProjectionList("o", projections, false);
        main.setProjection(projections);

        main.add(Restrictions.like("name.orig", "a%"));
        String expected = HibernateToSqlTranslator.toSql(main);

        SubstringFilter substring = SubstringFilter.createSubstring(ObjectType.F_NAME, ObjectType.class,
                prismContext, PolyStringOrigMatchingRule.NAME, "a");
        substring.setAnchorStart(true);
        String real = getInterpretedQuery(session, ObjectType.class, ObjectQuery.createObjectQuery(substring));

        LOGGER.info("exp. query>\n{}\nreal query>\n{}", new Object[] { expected, real });
        AssertJUnit.assertEquals(expected, real);

        OperationResult result = new OperationResult("test330queryUserSubstringName");
        int count = repositoryService.countObjects(ObjectType.class, ObjectQuery.createObjectQuery(substring),
                result);
        AssertJUnit.assertEquals(2, count);

        substring = SubstringFilter.createSubstring(ObjectType.F_NAME, ObjectType.class, prismContext,
                PolyStringOrigMatchingRule.NAME, "a");
        count = repositoryService.countObjects(ObjectType.class, ObjectQuery.createObjectQuery(substring),
                result);
        AssertJUnit.assertEquals(16, count);
    } finally {
        close(session);
    }
}