Example usage for org.hibernate.criterion Restrictions in

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

Introduction

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

Prototype

public static Criterion in(String propertyName, Collection values) 

Source Link

Document

Apply an "in" constraint to the named property.

Usage

From source file:com.eucalyptus.compute.common.internal.vm.VmInstance.java

License:Open Source License

public static Criterion criterion(VmState... state) {
    return Restrictions.in("state", state);
}

From source file:com.eucalyptus.compute.common.internal.vm.VmInstance.java

License:Open Source License

public static Criterion zoneCriterion(String... zone) {
    return Restrictions.in("placement.partitionName", zone);
}

From source file:com.eucalyptus.compute.service.ComputeService.java

License:Open Source License

/**
 *
 *///from   w  w  w.  j av a 2s .  c om
public DescribeVolumesResponseType describeVolumes(DescribeVolumesType request) throws Exception {
    final DescribeVolumesResponseType reply = request.getReply();
    final Context ctx = Contexts.lookup();

    final boolean showAll = request.getVolumeSet().remove("verbose");
    final Set<String> volumeIds = Sets.newLinkedHashSet(normalizeVolumeIdentifiers(request.getVolumeSet()));
    final AccountFullName ownerFullName = (ctx.isAdministrator() && (showAll || !volumeIds.isEmpty())) ? null
            : ctx.getUserFullName().asAccountFullName();

    final Filters.FiltersBuilder filtersBuilder = Filters.generateFor(request.getFilterSet(), Volume.class);
    if (!ctx.isAdministrator()) {
        filtersBuilder.withOptionalInternalFilter("system-managed", Collections.singleton("false"));
    }
    final Filter filter = filtersBuilder.generate();
    final Filter persistenceFilter = getPersistenceFilter(Volume.class, volumeIds, "volume-id", filter);
    final Predicate<? super Volume> requestedAndAccessible = CloudMetadatas.filteringFor(Volume.class)
            .byId(volumeIds).byPredicate(filter.asPredicate()).byPrivileges().buildPredicate();

    final Function<Set<String>, Pair<Set<String>, ArrayList<com.eucalyptus.compute.common.Volume>>> populateVolumeSet = new Function<Set<String>, Pair<Set<String>, ArrayList<com.eucalyptus.compute.common.Volume>>>() {
        public Pair<Set<String>, ArrayList<com.eucalyptus.compute.common.Volume>> apply(
                final Set<String> input) {
            final Set<String> allowedVolumeIds = Sets.newHashSet();
            final ArrayList<com.eucalyptus.compute.common.Volume> replyVolumes = Lists.newArrayList();
            final List<Volume> volumes = Entities.query(Volume.named(ownerFullName, null), true,
                    persistenceFilter.asCriterion(), persistenceFilter.getAliases());
            final Iterable<Volume> filteredVolumes = Iterables.filter(volumes,
                    Predicates.and(new TrackingPredicate<Volume>(volumeIds), requestedAndAccessible));

            // load attachment info
            final Criterion attachmentCriterion;
            final Map<String, String> attachmentAliases;
            if (Iterables.isEmpty(filteredVolumes)) {
                attachmentCriterion = Restrictions.disjunction();
                attachmentAliases = Collections.emptyMap();
            } else if (Iterables.size(Iterables.limit(filteredVolumes, 51)) < 50) { // small # load by id
                attachmentCriterion = Restrictions.in("volumeId",
                        Sets.newHashSet(Iterables.transform(filteredVolumes, RestrictedTypes.toDisplayName())));
                attachmentAliases = Collections.emptyMap();
            } else if (ownerFullName == null) { // load attachments for all accounts
                attachmentCriterion = Restrictions.conjunction();
                attachmentAliases = Collections.emptyMap();
            } else { // load all attachments for account
                attachmentCriterion = Restrictions.eq("vmInstance.ownerAccountNumber",
                        ownerFullName.getAccountNumber());
                ;
                attachmentAliases = Collections.singletonMap("vmInstance", "vmInstance");
            }
            final Map<String, VmVolumeAttachment> attachmentMap = CollectionUtils.putAll(
                    Iterables.concat(
                            Entities.query(VmBootVolumeAttachment.example(), true, attachmentCriterion,
                                    attachmentAliases),
                            Entities.query(VmStandardVolumeAttachment.example(), true, attachmentCriterion,
                                    attachmentAliases)),
                    Maps.<String, VmVolumeAttachment>newHashMap(), VmVolumeAttachment.volumeId(),
                    Functions.<VmVolumeAttachment>identity());

            // build response volumes
            for (final Volume foundVol : filteredVolumes) {
                allowedVolumeIds.add(foundVol.getDisplayName());
                if (State.ANNIHILATED.equals(foundVol.getState())) {
                    Entities.delete(foundVol);
                    replyVolumes.add(foundVol.morph(new com.eucalyptus.compute.common.Volume()));
                } else {
                    VmVolumeAttachment attachment = attachmentMap.get(foundVol.getDisplayName());
                    AttachedVolume attachedVolume = null;
                    if (attachment != null) {
                        attachedVolume = VmVolumeAttachment.asAttachedVolume(attachment.getVmInstance())
                                .apply(attachment);
                    } else {
                        if (State.BUSY.equals(foundVol.getState())) {
                            foundVol.setState(State.EXTANT);
                        }
                    }
                    com.eucalyptus.compute.common.Volume msgTypeVolume = foundVol
                            .morph(new com.eucalyptus.compute.common.Volume());
                    if (attachedVolume != null) {
                        msgTypeVolume.setStatus("in-use");
                        msgTypeVolume.getAttachmentSet().add(attachedVolume);
                    }
                    replyVolumes.add(msgTypeVolume);
                }
            }
            return Pair.pair(allowedVolumeIds, replyVolumes);
        }
    };

    final Pair<Set<String>, ArrayList<com.eucalyptus.compute.common.Volume>> volumeIdsAndVolumes = Entities
            .asTransaction(Volume.class, populateVolumeSet).apply(volumeIds);
    errorIfNotFound("InvalidVolume.NotFound", "volume", volumeIds);
    @SuppressWarnings("ConstantConditions")
    final Set<String> allowedVolumeIds = volumeIdsAndVolumes.getLeft();
    reply.setVolumeSet(volumeIdsAndVolumes.getRight());

    Map<String, List<Tag>> tagsMap = TagSupport.forResourceClass(Volume.class)
            .getResourceTagMap(AccountFullName.getInstance(ctx.getAccountNumber()), allowedVolumeIds);
    for (final com.eucalyptus.compute.common.Volume volume : reply.getVolumeSet()) {
        Tags.addFromTags(volume.getTagSet(), ResourceTag.class, tagsMap.get(volume.getVolumeId()));
    }

    return reply;
}

From source file:com.eucalyptus.compute.vpc.persist.PersistenceNatGateways.java

License:Open Source License

@Override
public long countByZone(final OwnerFullName ownerFullName, final String availabilityZone)
        throws VpcMetadataException {
    return countByExample(NatGateway.exampleWithOwner(ownerFullName),
            Restrictions.and(/*from w w w .  ja v a2 s  . c  o m*/
                    Restrictions.in("state", EnumSet.of(State.pending, State.available, State.deleting)),
                    Restrictions.eq("subnet.availabilityZone", availabilityZone)),
            Collections.singletonMap("subnet", "subnet"));
}

From source file:com.eucalyptus.entities.EntityCache.java

License:Open Source License

@SuppressWarnings({ "unchecked", "ConstantConditions" })
private void refresh() {
    final List<Pair<String, Integer>> currentKeys = loadVersionMap();
    cache.keySet().retainAll(currentKeys);
    currentKeys.removeAll(cache.keySet());
    for (List<Pair<String, Integer>> keyBatch : Iterables.partition(currentKeys, batchSize)) {
        try (final TransactionResource db = Entities.transactionFor(example)) {
            List<E> entities = (List<E>) Entities.createCriteria(example.getClass())
                    .add(Example.create(example)).setReadOnly(true).setCacheable(false).setFetchSize(batchSize)
                    .add(Restrictions.in("id",
                            Lists.newArrayList(Iterables.transform(keyBatch, Pair.<String, Integer>left()))))
                    .list();//from   ww w. j  a va2  s  .  c o m
            for (final E entity : entities) {
                cache.put(Pair.pair(getId(entity), entity.getVersion()), transformFunction.apply(entity));
            }
        }
    }
}

From source file:com.eucalyptus.tags.TagSupport.java

License:Open Source License

/**
 * Get the tags for the given resources, grouped by ID and ordered for display.
 * //from w w w  .j  a v a  2s.com
 * @param owner The account for the tags
 * @param identifiers The resource identifiers for the tags
 * @return The tag map with an entry for each requested resource
 */
public Map<String, List<Tag>> getResourceTagMap(final OwnerFullName owner, final Iterable<String> identifiers) {
    final Map<String, List<Tag>> tagMap = Maps.newHashMap();
    for (final String id : identifiers) {
        tagMap.put(id, Lists.<Tag>newArrayList());
    }
    if (!tagMap.isEmpty()) {
        final Tag example = example(owner);
        final DetachedCriteria detachedCriteria = DetachedCriteria.forClass(resourceClass)
                .add(Restrictions.in(resourceClassIdField, Lists.newArrayList(identifiers)))
                .setProjection(Projections.id());
        final Criterion idRestriction = Property.forName(tagClassResourceField).in(detachedCriteria);
        try {
            final List<Tag> tags = Tags.list(example, Predicates.alwaysTrue(), idRestriction,
                    Collections.<String, String>emptyMap());
            for (final Tag tag : tags) {
                tagMap.get(tag.getResourceId()).add(tag);
            }
        } catch (NoSuchMetadataException e) {
            log.error(e, e);
        }
        Ordering<Tag> order = Ordering.natural().onResultOf(Tags.key());
        for (final String id : identifiers) {
            Collections.sort(tagMap.get(id), order);
        }
    }
    return tagMap;
}

From source file:com.eucalyptus.vm.VmInstances.java

License:Open Source License

public static VmInstance lookupByPrivateIp(final String ip) throws NoSuchElementException {
    final EntityTransaction db = Entities.get(VmInstance.class);
    try {//from   w  ww . jav  a  2  s .  c o  m
        VmInstance vmExample = VmInstance.exampleWithPrivateIp(ip);
        VmInstance vm = (VmInstance) Entities.createCriteriaUnique(VmInstance.class)
                .add(Example.create(vmExample).enableLike(MatchMode.EXACT))
                .add(Restrictions.in("state", new VmState[] { VmState.RUNNING, VmState.PENDING }))
                .uniqueResult();
        if (vm == null) {
            throw new NoSuchElementException("VmInstance with private ip: " + ip);
        }
        db.commit();
        return vm;
    } catch (Exception ex) {
        Logs.exhaust().error(ex, ex);
        throw new NoSuchElementException(ex.getMessage());
    } finally {
        if (db.isActive())
            db.rollback();
    }
}

From source file:com.eucalyptus.vm.VmInstances.java

License:Open Source License

public static VmInstance lookupByPublicIp(final String ip) throws NoSuchElementException {
    final EntityTransaction db = Entities.get(VmInstance.class);
    try {/*from   w  w w . j a  v a 2 s  .  c o  m*/
        VmInstance vmExample = VmInstance.exampleWithPublicIp(ip);
        VmInstance vm = (VmInstance) Entities.createCriteriaUnique(VmInstance.class)
                .add(Example.create(vmExample).enableLike(MatchMode.EXACT))
                .add(Restrictions.in("state", new VmState[] { VmState.RUNNING, VmState.PENDING }))
                .uniqueResult();
        if (vm == null) {
            throw new NoSuchElementException("VmInstance with public ip: " + ip);
        }
        db.commit();
        return vm;
    } catch (Exception ex) {
        Logs.exhaust().error(ex, ex);
        throw new NoSuchElementException(ex.getMessage());
    } finally {
        if (db.isActive())
            db.rollback();
    }
}

From source file:com.evolveum.midpoint.repo.sql.query.restriction.InOidRestriction.java

License:Apache License

@Override
public Criterion interpret(InOidFilter filter) throws QueryException {
    String property = getContext().getAlias(null) + ".oid";

    return Restrictions.in(property, filter.getOids());
}

From source file:com.evolveum.midpoint.repo.sql.query.restriction.TypeRestriction.java

License:Apache License

@Override
public Criterion interpret(TypeFilter filter) throws QueryException {
    String property = getContext().getAlias(null) + "." + RObject.F_OBJECT_TYPE_CLASS;

    Set<RObjectType> values = getValues(filter.getType());

    Criterion basedOnType;//from   w w w. ja va2  s.c o  m
    if (values.size() > 1) {
        basedOnType = Restrictions.in(property, values);
    } else {
        basedOnType = Restrictions.eq(property, values.iterator().next());
    }

    if (filter.getFilter() == null) {
        return basedOnType;
    }

    QueryContext context = getContext();
    QueryInterpreter interpreter = context.getInterpreter();
    Restriction restriction = interpreter.findAndCreateRestriction(filter.getFilter(), context, this);
    Criterion basedOnFilter = restriction.interpret(filter.getFilter());

    return Restrictions.and(basedOnType, basedOnFilter);
}