List of usage examples for org.hibernate.criterion Restrictions and
public static LogicalExpression and(Criterion lhs, Criterion rhs)
From source file:com.eucalyptus.cloudformation.entity.StackEntityManager.java
License:Open Source License
public static StackEntity getAnyStackByNameOrId(String stackNameOrId, String accountId) { StackEntity stackEntity = null;/*ww w . ja v a2s . com*/ try (TransactionResource db = Entities.transactionFor(StackEntity.class)) { Criteria criteria = Entities.createCriteria(StackEntity.class) .add(Restrictions.eq("accountId", accountId)) // stack name or id can be stack name on non-deleted stacks or stack id on any stack .add(Restrictions.or( Restrictions.and(Restrictions.eq("recordDeleted", Boolean.FALSE), Restrictions.eq("stackName", stackNameOrId)), Restrictions.eq("stackId", stackNameOrId))); List<StackEntity> entityList = criteria.list(); if (entityList != null && !entityList.isEmpty()) { stackEntity = entityList.get(0); } db.commit(); } return stackEntity; }
From source file:com.eucalyptus.cloudformation.entity.StackResourceEntityManager.java
License:Open Source License
public static StackResourceEntity describeStackResource(String accountId, String stackNameOrId, String logicalResourceId) throws CloudFormationException { StackResourceEntity matchingStackResourceEntity = null; String stackId = null;/* w ww .jav a2 s .com*/ try (TransactionResource db = Entities.transactionFor(StackResourceEntity.class)) { // There is some weirdness in this request. The stack name represents either the stack name of the // non-deleted stack or the stack id of the deleted or non-deleted stack. Criteria criteria = Entities.createCriteria(StackResourceEntity.class) .add(Restrictions.eq("accountId", accountId)) .add(Restrictions.or( Restrictions.and(Restrictions.eq("recordDeleted", Boolean.FALSE), Restrictions.eq("stackName", stackNameOrId)), Restrictions.eq("stackId", stackNameOrId))) .add(Restrictions.ne("resourceStatus", StackResourceEntity.Status.NOT_STARTED)); // placeholder, AWS doesn't return these List<StackResourceEntity> result = criteria.list(); if (result == null || result.isEmpty()) { // TODO: in theory the stack may exist but with no resources. Either way though there is an error, so this is ok. throw new ValidationErrorException("Stack with name " + stackNameOrId + " does not exist"); } for (StackResourceEntity stackResourceEntity : result) { if (stackId == null) { stackId = stackResourceEntity.getStackId(); } else if (!stackId.equals(stackResourceEntity.getStackId())) { throw new InternalFailureException("Got results from more than one stack"); } if (logicalResourceId.equals(stackResourceEntity.getLogicalResourceId())) { if (matchingStackResourceEntity != null) { throw new InternalFailureException("More than one record exists for Resource " + logicalResourceId + " on stack " + stackId); } else { matchingStackResourceEntity = stackResourceEntity; } } } if (matchingStackResourceEntity == null) { throw new ValidationErrorException( "Resource " + logicalResourceId + " does not exist for stack " + stackId); } db.commit(); } return matchingStackResourceEntity; }
From source file:com.eucalyptus.cloudformation.entity.StackResourceEntityManager.java
License:Open Source License
public static List<StackResourceEntity> describeStackResources(String accountId, String stackNameOrId, String physicalResourceId, String logicalResourceId) { List<StackResourceEntity> returnValue = null; String stackId = null;//from w w w . j av a 2 s. c o m try (TransactionResource db = Entities.transactionFor(StackResourceEntity.class)) { // There is some weirdness in this request. The stack name represents either the stack name of the // non-deleted stack or the stack id of the deleted or non-deleted stack. Criteria criteria = Entities.createCriteria(StackResourceEntity.class) .add(Restrictions.eq("accountId", accountId)); if (stackNameOrId != null) { criteria.add(Restrictions.or( Restrictions.and(Restrictions.eq("recordDeleted", Boolean.FALSE), Restrictions.eq("stackName", stackNameOrId)), Restrictions.eq("stackId", stackNameOrId))); } if (logicalResourceId != null) { criteria.add(Restrictions.eq("logicalResourceId", logicalResourceId)); } if (physicalResourceId != null) { criteria.add(Restrictions.eq("physicalResourceId", logicalResourceId)); } criteria.add(Restrictions.ne("resourceStatus", StackResourceEntity.Status.NOT_STARTED)); // placeholder, AWS doesn't return these returnValue = criteria.list(); db.commit(); } return returnValue; }
From source file:com.eucalyptus.cluster.service.fake.FakeNodeService.java
License:Open Source License
private void reload() { try (final TransactionResource tx = Entities.readOnlyDistinctTransactionFor(VmInstance.class)) { for (final VmInstance instance : VmInstances.list(null, Restrictions.and(VmInstance.criterion(VmInstance.VmStateSet.RUN.array()), VmInstance.serviceTagCriterion(node.getServiceTag())), Collections.emptyMap(), VmInstance.VmStateSet.RUN, false)) { final VmInfo fakeVmInfo = new VmInfo(instance.getInstanceId(), instance.getInstanceUuid(), instance.getReservationId(), instance.getLaunchIndex(), instance.getVmType().getName(), instance.getVmType().getCpu(), instance.getVmType().getDisk(), instance.getVmType().getMemory(), instance.getPlatform(), instance.getKeyPair().getPublicKey(), instance.getCreationTimestamp().getTime(), "Extant", instance.getLastUpdateTimestamp().getTime(), instance.getNetworkInterfaces().stream().findFirst().map(NetworkInterface::getDisplayName) .<String>orElse(null), instance.getNetworkInterfaces().stream().findFirst() .map(ni -> ni.getAttachment().getAttachmentId()).orElse(null), instance.getMacAddress(), instance.getPrivateAddress(), null, instance.getOwnerUserId(), instance.getOwnerAccountNumber(), instance.getVpcId()); instance.getNetworkInterfaces().stream().skip(1).collect(Collectors.toMap( FUtils.chain(NetworkInterface::getAttachment, NetworkInterfaceAttachment::getDeviceIndex), ni -> new VmInterface(ni.getDisplayName(), ni.getAttachment().getAttachmentId(), ni.getAttachment().getDeviceIndex(), ni.getMacAddress(), ni.getPrivateIpAddress(), Optional.ofNullable(ni.getAssociation()) .map(NetworkInterfaceAssociation::getPublicIp).<String>orElse(null)), (v1, v2) -> v1, fakeVmInfo::getSecondaryInterfaceAttachments)); for (com.eucalyptus.compute.common.internal.vm.VmVolumeAttachment attachment : Iterables.concat( instance.getBootRecord().getPersistentVolumes(), instance.getTransientVolumeState().getAttachments())) { fakeVmInfo.getVolumeAttachments().put(attachment.getVolumeId(), new VmVolumeAttachment(attachment.getAttachTime().getTime(), attachment.getVolumeId(), attachment.getDevice(), attachment.getRemoteDevice(), "attached")); }/*from w ww .j av a 2 s . c om*/ node.vm(fakeVmInfo); } } }
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( 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.compute.vpc.VpcWorkflow.java
License:Open Source License
/** * Release resources for failed NAT gateways *//*ww w . j a va 2s.com*/ private void natGatewayFailureCleanup() { List<String> failedNatGatewayIds = Collections.emptyList(); try (final TransactionResource tx = Entities.transactionFor(NatGateway.class)) { failedNatGatewayIds = natGateways.list(null, Restrictions.and(Example.create(NatGateway.exampleWithState(NatGateway.State.failed)), Restrictions.isNotNull("networkInterfaceId")), Collections.<String, String>emptyMap(), Predicates.<NatGateway>alwaysTrue(), CloudMetadatas.<NatGateway>toDisplayName()); } catch (final Exception e) { logger.error("Error listing failed NAT gateways for cleanup", e); } for (final String natGatewayId : failedNatGatewayIds) { try (final TransactionResource tx = Entities.transactionFor(NatGateway.class)) { final NatGateway natGateway = natGateways.lookupByName(null, natGatewayId, Functions.<NatGateway>identity()); releaseNatGatewayResources(natGateway); tx.commit(); } catch (Exception e) { if (PersistenceExceptions.isStaleUpdate(e)) { logger.debug("Conflict updating NAT gateway " + natGatewayId + " for cleanup (will retry)"); } else { logger.error("Error cleaning up failed NAT gateway " + natGatewayId, e); } } } }
From source file:com.eucalyptus.compute.vpc.VpcWorkflow.java
License:Open Source License
/** * Delete NAT gateways that have timed out in a terminal state (failed or deleted) */// w ww .j a v a2s. c o m private void natGatewayTimeout() { List<String> timedOutNatGateways = Collections.emptyList(); try (final TransactionResource tx = Entities.transactionFor(NatGateway.class)) { timedOutNatGateways = natGateways.list(null, Restrictions.and( Restrictions.or(Example.create(NatGateway.exampleWithState(NatGateway.State.failed)), Example.create(NatGateway.exampleWithState(NatGateway.State.deleted))), Restrictions.lt("lastUpdateTimestamp", new Date(System.currentTimeMillis() - NatGateways.EXPIRY_AGE))), Collections.<String, String>emptyMap(), Predicates.<NatGateway>alwaysTrue(), CloudMetadatas.<NatGateway>toDisplayName()); } catch (final Exception e) { logger.error("Error listing timed out NAT gateways", e); } for (final String natGatewayId : timedOutNatGateways) { try (final TransactionResource tx = Entities.transactionFor(NatGateway.class)) { final NatGateway natGateway = natGateways.lookupByName(null, natGatewayId, Functions.<NatGateway>identity()); logger.info("Deleting NAT gateway " + natGateway.getDisplayName() + " with state " + natGateway.getState()); natGateways.delete(natGateway); tx.commit(); } catch (final VpcMetadataNotFoundException e) { logger.info("NAT gateway " + natGatewayId + " not found for deletion"); } catch (final Exception e) { logger.error("Error deleting timed out NAT gateway " + natGatewayId, e); } } }
From source file:com.eucalyptus.objectstorage.DbObjectManagerImpl.java
License:Open Source License
@Override public long countValid(Bucket bucket) throws Exception { /*//w ww . j ava2 s . c om * Returns all entries, pending delete or not. */ EntityTransaction db = Entities.get(ObjectEntity.class); ObjectEntity exampleObject = new ObjectEntity(bucket.getBucketName(), null, null); Criterion crit = Restrictions.and(ObjectEntity.QueryHelpers.getNotDeletingRestriction(), ObjectEntity.QueryHelpers.getNotPendingRestriction()); try { return Entities.count(exampleObject, crit, new HashMap<String, String>()); } catch (Throwable e) { LOG.error("Error getting object count for bucket " + bucket.getBucketName(), e); throw new Exception(e); } finally { db.rollback(); } }
From source file:com.eucalyptus.objectstorage.metadata.DbObjectMetadataManagerImpl.java
License:Open Source License
@Override public List<ObjectEntity> lookupObjectsForReaping(Bucket bucket, String objectKeyPrefix, Date age) { List<ObjectEntity> results; try (TransactionResource tran = Entities.transactionFor(ObjectEntity.class)) { // setup example and criteria ObjectEntity example = new ObjectEntity().withState(ObjectState.extant).withBucket(bucket); Criteria search = Entities.createCriteria(ObjectEntity.class).add(Example.create(example)); search.add(Restrictions.and(Restrictions.like("objectKey", objectKeyPrefix, MatchMode.START), Restrictions.lt("creationTimestamp", age))); search = getSearchByBucket(search, bucket); results = search.list();// ww w . j a v a 2 s . c o m tran.commit(); } catch (Exception ex) { LOG.error("exception caught while retrieving objects prefix with " + objectKeyPrefix + " from bucket " + bucket.getBucketName() + ", error message - " + ex.getMessage()); return Collections.EMPTY_LIST; } return results; }
From source file:com.eucalyptus.objectstorage.metadata.DbObjectMetadataManagerImpl.java
License:Open Source License
@Override public PaginatedResult<ObjectEntity> listVersionsPaginated(final Bucket bucket, int maxEntries, String prefix, String delimiter, String fromKeyMarker, String fromVersionId, boolean latestOnly) throws Exception { EntityTransaction db = Entities.get(ObjectEntity.class); try {//from www . j ava2s .c o m PaginatedResult<ObjectEntity> result = new PaginatedResult<ObjectEntity>(); HashSet<String> commonPrefixes = new HashSet<String>(); // Include zero since 'istruncated' is still valid if (maxEntries >= 0) { final int queryStrideSize = maxEntries + 1; ObjectEntity searchObj = new ObjectEntity().withBucket(bucket).withState(ObjectState.extant); // Return latest version, so exclude delete markers as well. // This makes listVersion act like listObjects if (latestOnly) { searchObj.setIsLatest(true); searchObj.setIsDeleteMarker(false); } Criteria objCriteria = Entities.createCriteria(ObjectEntity.class); objCriteria.setReadOnly(true); objCriteria.setFetchSize(queryStrideSize); objCriteria.add(Example.create(searchObj)); objCriteria.addOrder(Order.asc("objectKey")); objCriteria.addOrder(Order.desc("objectModifiedTimestamp")); objCriteria.setMaxResults(queryStrideSize); if (!Strings.isNullOrEmpty(fromKeyMarker)) { if (!Strings.isNullOrEmpty(fromVersionId)) { // Look for the key that matches the key-marker and version-id-marker ObjectEntity searchObject = new ObjectEntity(bucket, fromKeyMarker, fromVersionId); ObjectEntity matchingObject = null; try { matchingObject = Entities.uniqueResult(searchObject); if (matchingObject == null || matchingObject.getObjectModifiedTimestamp() == null) { throw new NoSuchKeyException(bucket.getBucketName() + "/" + fromKeyMarker + "?versionId=" + fromVersionId); } } catch (Exception e) { LOG.warn("No matching object found for key-marker=" + fromKeyMarker + " and version-id-marker=" + fromVersionId); throw new NoSuchKeyException( bucket.getBucketName() + "/" + fromKeyMarker + "?versionId=" + fromVersionId); } // The result set should be exclusive of the key with the key-marker version-id-marker pair. Look for keys that chronologically // follow the version-id-marker for the given key-marker and also the keys that follow the key-marker. objCriteria.add(Restrictions.or( Restrictions.and(Restrictions.eq("objectKey", fromKeyMarker), Restrictions.lt("objectModifiedTimestamp", matchingObject.getObjectModifiedTimestamp())), Restrictions.gt("objectKey", fromKeyMarker))); } else { // No version-id-marker, just set the criteria the key-marker objCriteria.add(Restrictions.gt("objectKey", fromKeyMarker)); } } else { // No criteria to be set } if (!Strings.isNullOrEmpty(prefix)) { objCriteria.add(Restrictions.like("objectKey", prefix, MatchMode.START)); } else { prefix = ""; } objCriteria = getSearchByBucket(objCriteria, bucket); // Ensure not null. if (Strings.isNullOrEmpty(delimiter)) { delimiter = ""; } List<ObjectEntity> objectInfos = null; int resultKeyCount = 0; String[] parts = null; String prefixString = null; boolean useDelimiter = !Strings.isNullOrEmpty(delimiter); int pages = 0; // Iterate over result sets of size maxkeys + 1 since // commonPrefixes collapse the list, we may examine many more // records than maxkeys + 1 do { parts = null; prefixString = null; // Skip ahead the next page of 'queryStrideSize' results. objCriteria.setFirstResult(pages++ * queryStrideSize); objectInfos = (List<ObjectEntity>) objCriteria.list(); if (objectInfos == null) { // nothing to do. break; } for (ObjectEntity objectRecord : objectInfos) { if (useDelimiter) { // Check if it will get aggregated as a commonprefix parts = objectRecord.getObjectKey().substring(prefix.length()).split(delimiter); if (parts.length > 1) { prefixString = prefix + parts[0] + delimiter; if (!prefixString.equals(fromKeyMarker) && !commonPrefixes.contains(prefixString)) { if (resultKeyCount == maxEntries) { // This is a new record, so we know // we're truncating if this is true result.setIsTruncated(true); resultKeyCount++; break; } else { // Add it to the common prefix set commonPrefixes.add(prefixString); result.setLastEntry(prefixString); // count the unique commonprefix as a // single return entry resultKeyCount++; } } else { // Already have this prefix, so skip } continue; } } if (resultKeyCount == maxEntries) { // This is a new (non-commonprefix) record, so // we know we're truncating result.setIsTruncated(true); resultKeyCount++; break; } result.getEntityList().add(objectRecord); result.setLastEntry(objectRecord); resultKeyCount++; } if (resultKeyCount <= maxEntries && objectInfos.size() <= maxEntries) { break; } } while (resultKeyCount <= maxEntries); // Sort the prefixes from the hashtable and add to the reply if (commonPrefixes != null) { result.getCommonPrefixes().addAll(commonPrefixes); Collections.sort(result.getCommonPrefixes()); } } else { throw new IllegalArgumentException("MaxKeys must be positive integer"); } return result; } catch (Exception e) { LOG.error("Error generating paginated object list of bucket " + bucket.getBucketName(), e); throw e; } finally { db.rollback(); } }