Example usage for org.hibernate.criterion Restrictions and

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

Introduction

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

Prototype

public static LogicalExpression and(Criterion lhs, Criterion rhs) 

Source Link

Document

Return the conjuction of two expressions

Usage

From source file:com.eucalyptus.auth.DatabaseAuthProvider.java

License:Open Source License

/**
 * Lookup enabled user by its access key ID. Only return the user if the key is active.
 * /*from   www.  ja  v  a  2s.com*/
 * @param keyId
 * @return
 * @throws AuthException
 */
@Override
public User lookupUserByAccessKeyId(String keyId) throws AuthException {
    if (keyId == null || "".equals(keyId)) {
        throw new AuthException("Empty key ID");
    }
    EntityWrapper<UserEntity> db = EntityWrapper.get(UserEntity.class);
    try {
        @SuppressWarnings("unchecked")
        UserEntity result = (UserEntity) db.createCriteria(UserEntity.class).setCacheable(true)
                .add(Restrictions.eq("enabled", true)).createCriteria("keys").setCacheable(true)
                .add(Restrictions.and(Restrictions.eq("accessKey", keyId), Restrictions.eq("active", true)))
                .setReadOnly(true).uniqueResult();
        if (result == null) {
            throw new NoSuchElementException("Can not find user with key " + keyId);
        }
        return new DatabaseUserProxy(result);
    } catch (Exception e) {
        Debugging.logError(LOG, e, "Failed to find user with access key ID : " + keyId);
        throw new AuthException(AuthException.NO_SUCH_USER, e);
    } finally {
        db.rollback();
    }
}

From source file:com.eucalyptus.auth.DatabaseAuthProvider.java

License:Open Source License

/**
 * Lookup enabled user by its certificate. Only return the user if the certificate is active and not revoked.
 * //  w  w  w.j  ava  2s  . co  m
 * @param cert
 * @return
 * @throws AuthException
 */
@Override
public User lookupUserByCertificate(X509Certificate cert) throws AuthException {
    if (cert == null) {
        throw new AuthException("Empty input cert");
    }
    EntityWrapper<UserEntity> db = EntityWrapper.get(UserEntity.class);
    try {
        @SuppressWarnings("unchecked")
        UserEntity result = (UserEntity) db.createCriteria(UserEntity.class).setCacheable(true)
                .add(Restrictions.eq("enabled", true)).createCriteria("certificates").setCacheable(true)
                .add(Restrictions.and(Restrictions.eq("pem", X509CertHelper.fromCertificate(cert)),
                        Restrictions.and(Restrictions.eq("active", true), Restrictions.eq("revoked", false))))
                .setReadOnly(true).uniqueResult();
        if (result == null) {
            throw new NoSuchElementException("Can not find user with specific cert");
        }
        return new DatabaseUserProxy(result);
    } catch (Exception e) {
        Debugging.logError(LOG, e, "Failed to find user with certificate : " + cert);
        throw new AuthException(AuthException.NO_SUCH_USER, e);
    } finally {
        db.rollback();
    }
}

From source file:com.eucalyptus.auth.DatabaseRoleProxy.java

License:Open Source License

@Override
public List<Authorization> lookupAuthorizations(final String resourceType) throws AuthException {
    if (resourceType == null) {
        throw new AuthException("Empty resource type");
    }/*from  w  ww.j a  v  a2  s.co  m*/
    final EntityWrapper<AuthorizationEntity> db = EntityWrapper.get(AuthorizationEntity.class);
    try {
        @SuppressWarnings("unchecked")
        final List<AuthorizationEntity> authorizations = (List<AuthorizationEntity>) db
                .createCriteria(AuthorizationEntity.class)
                .add(Restrictions.and(
                        Restrictions.or(Restrictions.eq("type", resourceType), Restrictions.eq("type", "*")),
                        Restrictions.in("effect",
                                EnumSet.of(Authorization.EffectType.Allow, Authorization.EffectType.Deny))))
                .createCriteria("statement").createCriteria("policy").createCriteria("role")
                .add(Restrictions.eq("roleId", getRoleId())).setCacheable(true).list();
        final List<Authorization> results = Lists.newArrayList();
        for (final AuthorizationEntity auth : authorizations) {
            results.add(new DatabaseAuthorizationProxy(auth));
        }
        return results;
    } catch (Exception e) {
        Debugging.logError(LOG, e,
                "Failed to lookup authorization for user with ID " + getRoleId() + ", type=" + resourceType);
        throw new AuthException("Failed to lookup auth", e);
    } finally {
        if (db.isActive())
            db.rollback();
    }
}

From source file:com.eucalyptus.auth.DatabaseRoleProxy.java

License:Open Source License

@Override
public List<Authorization> lookupQuotas(final String resourceType) throws AuthException {
    final EntityWrapper<AuthorizationEntity> db = EntityWrapper.get(AuthorizationEntity.class);
    try {/*from   www. j  a  v a 2s .co  m*/
        @SuppressWarnings("unchecked")
        final List<AuthorizationEntity> authorizations = (List<AuthorizationEntity>) db
                .createCriteria(AuthorizationEntity.class)
                .add(Restrictions.and(Restrictions.eq("type", resourceType),
                        Restrictions.eq("effect", Authorization.EffectType.Limit)))
                .createCriteria("statement").createCriteria("policy").createCriteria("role")
                .add(Restrictions.eq("roleId", getRoleId())).setCacheable(true).list();
        final List<Authorization> results = Lists.newArrayList();
        for (AuthorizationEntity auth : authorizations) {
            results.add(new DatabaseAuthorizationProxy(auth));
        }
        return results;
    } catch (Exception e) {
        Debugging.logError(LOG, e,
                "Failed to lookup quotas for user with ID " + getRoleId() + ", type=" + resourceType);
        throw new AuthException("Failed to lookup quota", e);
    } finally {
        if (db.isActive())
            db.rollback();
    }
}

From source file:com.eucalyptus.auth.DatabaseUserProxy.java

License:Open Source License

@Override
public List<Authorization> lookupAuthorizations(String resourceType) throws AuthException {
    String userId = this.delegate.getUserId();
    if (resourceType == null) {
        throw new AuthException("Empty resource type");
    }/*  w w w .  j  a v a  2  s  .  co m*/
    EntityWrapper<AuthorizationEntity> db = EntityWrapper.get(AuthorizationEntity.class);
    try {
        @SuppressWarnings("unchecked")
        List<AuthorizationEntity> authorizations = (List<AuthorizationEntity>) db
                .createCriteria(AuthorizationEntity.class).setCacheable(true)
                .add(Restrictions.and(Restrictions.eq("type", resourceType),
                        Restrictions.or(Restrictions.eq("effect", EffectType.Allow),
                                Restrictions.eq("effect", EffectType.Deny))))
                .createCriteria("statement").setCacheable(true).createCriteria("policy").setCacheable(true)
                .createCriteria("group").setCacheable(true).createCriteria("users").setCacheable(true)
                .add(Restrictions.eq("userId", userId)).list();
        db.commit();
        List<Authorization> results = Lists.newArrayList();
        for (AuthorizationEntity auth : authorizations) {
            results.add(new DatabaseAuthorizationProxy(auth));
        }
        return results;
    } catch (Exception e) {
        db.rollback();
        Debugging.logError(LOG, e,
                "Failed to lookup authorization for user with ID " + userId + ", type=" + resourceType);
        throw new AuthException("Failed to lookup auth", e);
    }
}

From source file:com.eucalyptus.auth.DatabaseUserProxy.java

License:Open Source License

@Override
public List<Authorization> lookupQuotas(String resourceType) throws AuthException {
    String userId = this.delegate.getUserId();
    EntityWrapper<AuthorizationEntity> db = EntityWrapper.get(AuthorizationEntity.class);
    try {// w  w w  .  j a  v a  2 s .c  om
        @SuppressWarnings("unchecked")
        List<AuthorizationEntity> authorizations = (List<AuthorizationEntity>) db
                .createCriteria(AuthorizationEntity.class).setCacheable(true)
                .add(Restrictions.and(Restrictions.eq("type", resourceType),
                        Restrictions.eq("effect", EffectType.Limit)))
                .createCriteria("statement").setCacheable(true).createCriteria("policy").setCacheable(true)
                .createCriteria("group").setCacheable(true).createCriteria("users")
                .add(Restrictions.eq("userId", userId)).list();
        db.commit();
        List<Authorization> results = Lists.newArrayList();
        for (AuthorizationEntity auth : authorizations) {
            results.add(new DatabaseAuthorizationProxy(auth));
        }
        return results;
    } catch (Exception e) {
        db.rollback();
        Debugging.logError(LOG, e,
                "Failed to lookup quotas for user with ID " + userId + ", type=" + resourceType);
        throw new AuthException("Failed to lookup quota", e);
    }
}

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

License:Open Source License

private SnapshotInfo fetchPreviousSnapshot(int maxDeltas) throws Exception {

    SnapshotInfo prevSnapToAssign = null;
    SnapshotInfo currSnap = Transactions.find(new SnapshotInfo(snapshotId));

    try (TransactionResource tr = Entities.transactionFor(SnapshotInfo.class)) {

        // Find the most recent snapshot that is not in one of the states that
        // is ineligible to use for creating a snap delta.  
        SnapshotInfo prevEligibleSnapSearch = new SnapshotInfo();
        prevEligibleSnapSearch.setVolumeId(currSnap.getVolumeId());
        Criteria search = Entities.createCriteria(SnapshotInfo.class);
        search.add(Example.create(prevEligibleSnapSearch).enableLike(MatchMode.EXACT));
        search.add(Restrictions.and(StorageProperties.SNAPSHOT_DELTA_GENERATION_CRITERION,
                Restrictions.lt("startTime", currSnap.getStartTime())));
        search.addOrder(Order.desc("startTime"));
        search.setReadOnly(true);// w  w w  .  ja  va 2 s  .  co  m
        search.setMaxResults(1); // only return the latest one

        List<SnapshotInfo> prevEligibleSnapList = (List<SnapshotInfo>) search.list();

        boolean committed = false;

        if (prevEligibleSnapList != null && prevEligibleSnapList.size() > 0
                && (prevSnapToAssign = prevEligibleSnapList.get(0)) != null) {
            // Found an eligible previous snapshot to use as a parent for this 
            // snapshot, if we make it a delta.
            if (prevSnapToAssign.getSnapshotLocation() != null && prevSnapToAssign.getIsOrigin() != null) {
                LOG.info(this.volumeId
                        + " has been snapshotted and uploaded before. Most recent such snapshot is "
                        + prevSnapToAssign.getSnapshotId());

                // Get all the restorable snapshots for this volume, earlier than the current snapshot
                SnapshotInfo prevRestorableSnapsSearch = new SnapshotInfo();
                prevRestorableSnapsSearch.setVolumeId(currSnap.getVolumeId());
                search = Entities.createCriteria(SnapshotInfo.class);
                search.add(Example.create(prevRestorableSnapsSearch).enableLike(MatchMode.EXACT));
                search.add(Restrictions.and(StorageProperties.SNAPSHOT_DELTA_RESTORATION_CRITERION,
                        Restrictions.lt("startTime", currSnap.getStartTime())));
                search.addOrder(Order.desc("startTime"));
                search.setReadOnly(true);
                List<SnapshotInfo> prevRestorableSnapsList = (List<SnapshotInfo>) search.list();
                tr.commit();
                committed = true;

                // Get the snap chain ending with the previous snapshot (not the current)
                List<SnapshotInfo> snapChain = blockStorageUtilSvc.getSnapshotChain(prevRestorableSnapsList,
                        prevSnapToAssign.getSnapshotId());
                int numDeltas = 0;
                if (snapChain == null || snapChain.size() == 0) {
                    // This should never happen. The chain should always include the 
                    // parent (previous) snapshot we already found. But create it as a 
                    // full snapshot instead of failing, to account for the unknown case
                    // that might not prevent an OK full snapshot.
                    LOG.error("Did not find the current snapshot's previous snapshot "
                            + prevSnapToAssign.getSnapshotId() + " in the restorable snapshots list. "
                            + "The current snapshot " + currSnap.getSnapshotId()
                            + " will be created as a full snapshot.");
                } else if (snapChain.get(0).getPreviousSnapshotId() != null) {
                    // This should never happen. The first snapshot in the chain
                    // should always be a full snapshot. But create it as a 
                    // full snapshot instead of failing, to account for the unknown case
                    // that might not prevent an OK full snapshot.
                    LOG.error("First snapshot " + snapChain.get(0).getSnapshotId() + " in the chain of "
                            + snapChain.size() + " snapshots is not a full snapshot. The current snapshot "
                            + currSnap.getSnapshotId() + " will be created as a full snapshot.");
                } else {
                    numDeltas = snapChain.size() - 1;
                    LOG.info(this.volumeId + " has " + numDeltas
                            + " delta(s) since the last full checkpoint. Max limit is " + maxDeltas);
                    if (numDeltas < maxDeltas) {
                        return prevSnapToAssign;
                    }
                }
            } else {
                LOG.info(this.volumeId
                        + " has not been snapshotted and/or uploaded after the support for incremental snapshots was added");
            }
        } else {
            LOG.info(this.volumeId + " has no prior active snapshots in the system");
        }
        if (!committed) {
            tr.commit();
        }
    } catch (Exception e) {
        LOG.warn("Failed to look up previous snapshots for " + this.volumeId, e); // return null on exception, forces entire snapshot to get uploaded
    }
    return null;
}

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);/*from  w  ww.j  a v  a 2s  .  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.cloudformation.entity.StackEntityManager.java

License:Open Source License

public static List<StackEntity> describeStacks(String accountId, String stackNameOrId) {
    List<StackEntity> returnValue = Lists.newArrayList();
    try (TransactionResource db = Entities.transactionFor(StackEntity.class)) {
        Criteria criteria = Entities.createCriteria(StackEntity.class)
                .add(Restrictions.eq("accountId", accountId));
        if (stackNameOrId != null) {
            // stack name or id can be stack name on non-deleted stacks or stack id on any stack
            criteria.add(Restrictions.or(
                    Restrictions.and(Restrictions.eq("recordDeleted", Boolean.FALSE),
                            Restrictions.eq("stackName", stackNameOrId)),
                    Restrictions.eq("stackId", stackNameOrId)));
        } else {/*from www .  j  a  va 2s .com*/
            criteria.add(Restrictions.eq("recordDeleted", Boolean.FALSE));
        }
        returnValue = criteria.list();
        db.commit();
    }
    return returnValue;
}