List of usage examples for org.hibernate.criterion Restrictions isNull
public static Criterion isNull(String propertyName)
From source file:com.eucalyptus.cloudwatch.domain.listmetrics.ListMetricManager.java
License:Open Source License
private static void addMetric(EntityTransaction db, String accountId, String metricName, String namespace, Map<String, String> dimensionMap, MetricType metricType) { List<ListMetric> foldedMetrics = foldMetric(accountId, metricName, namespace, dimensionMap, metricType); for (ListMetric metric : foldedMetrics) { Criteria criteria = Entities.createCriteria(ListMetric.class) .add(Restrictions.eq("accountId", metric.getAccountId())) .add(Restrictions.eq("metricName", metric.getMetricName())) .add(Restrictions.eq("namespace", metric.getNamespace())); // add dimension restrictions int dimIndex = 1; for (DimensionEntity d : metric.getDimensions()) { criteria.add(Restrictions.eq("dim" + dimIndex + "Name", d.getName())); criteria.add(Restrictions.eq("dim" + dimIndex + "Value", d.getValue())); dimIndex++;//from w ww. j av a 2s . c o m } while (dimIndex <= ListMetric.MAX_DIM_NUM) { criteria.add(Restrictions.isNull("dim" + dimIndex + "Name")); criteria.add(Restrictions.isNull("dim" + dimIndex + "Value")); dimIndex++; } ListMetric inDbMetric = (ListMetric) criteria.uniqueResult(); if (inDbMetric != null) { inDbMetric.setVersion(1 + inDbMetric.getVersion()); } else { Entities.persist(metric); } } }
From source file:com.eucalyptus.compute.common.internal.vm.VmInstance.java
License:Open Source License
public static Criterion nullNodeCriterion() { return Restrictions.isNull("runtimeState.serviceTag"); }
From source file:com.eucalyptus.objectstorage.DbObjectManagerImpl.java
License:Open Source License
/** * Returns the list of entities currently pending writes. List returned is * in no particular order. Caller must order if required. * // w w w. jav a 2 s . c om * @param bucketName * @param objectKey * @param versionId * @return * @throws TransactionException */ public List<ObjectEntity> getPendingWrites(Bucket bucket, String objectKey, String versionId) throws Exception { try { // Return the latest version based on the created date. EntityTransaction db = Entities.get(ObjectEntity.class); try { ObjectEntity searchExample = new ObjectEntity(bucket.getBucketName(), objectKey, versionId); Criteria search = Entities.createCriteria(ObjectEntity.class); List results = search.add(Example.create(searchExample)) .add(Restrictions.isNull("objectModifiedTimestamp")).list(); db.commit(); return (List<ObjectEntity>) results; } finally { if (db != null && db.isActive()) { db.rollback(); } } } catch (NoSuchElementException e) { // Nothing, return empty list return new ArrayList<ObjectEntity>(0); } catch (Exception e) { LOG.error("Error fetching pending write records for object " + bucket.getBucketName() + "/" + objectKey + "?versionId=" + versionId); throw e; } }
From source file:com.eucalyptus.walrus.WalrusFSManager.java
License:Open Source License
public UploadPartResponseType uploadPart(UploadPartType request) throws WalrusException { UploadPartResponseType reply = (UploadPartResponseType) request.getReply(); Context ctx = Contexts.lookup(); Account account = ctx.getAccount();//from w w w. j a v a 2 s. co m String bucketName = request.getBucket(); String objectKey = request.getKey(); String key = bucketName + "." + objectKey; String randomKey = request.getRandomKey(); String uploadId = request.getUploadId(); Integer partNumber = Integer.parseInt(request.getPartNumber()); WalrusDataMessenger messenger = WalrusRESTBinding.getWriteMessenger(); Date lastModified = null; String md5 = new String(); Long oldBucketSize = 0L; //TODO compute this correctly later EntityWrapper<BucketInfo> db = EntityWrapper.get(BucketInfo.class); BucketInfo bucketInfo = new BucketInfo(bucketName); List<BucketInfo> bucketList = db.queryEscape(bucketInfo); if (bucketList.size() > 0) { BucketInfo bucket = bucketList.get(0); BucketLogData logData = bucket.getLoggingEnabled() ? request.getLogData() : null; long objSize = 0; try { objSize = Long.valueOf(request.getContentLength()); } catch (NumberFormatException e) { LOG.error("Invalid content length " + request.getContentLength()); //TODO: FIXME This should be a MissingContentLengthException throw new InternalErrorException("Missing Content-Length"); } String objectName = null; PartInfo partInfo = null; try { PartInfo searchManifest = new PartInfo(bucketName, objectKey); searchManifest.setUploadId(uploadId); searchManifest.setCleanup(Boolean.FALSE); EntityWrapper<PartInfo> dbPart = db.recast(PartInfo.class); Criteria partCriteria = dbPart.createCriteria(PartInfo.class); partCriteria.add(Example.create(searchManifest)); partCriteria.add(Restrictions.isNull("partNumber")); List<PartInfo> found = partCriteria.list(); if (found.size() == 0) { db.rollback(); throw new InternalErrorException( "Multipart upload ID is invalid. Intitiate a multipart upload request before uploading the parts"); } if (found.size() > 1) { db.rollback(); throw new InternalErrorException("Multiple manifests found for same uploadId"); } PartInfo foundManifest = found.get(0); partInfo = PartInfo.create(bucketName, objectKey, account); partInfo.setUploadId(uploadId); partInfo.setPartNumber(partNumber); partInfo.setCleanup(Boolean.FALSE); objectName = partInfo.getObjectName(); dbPart.add(partInfo); dbPart.commit(); } catch (Exception ex) { throw new InternalErrorException(ex); } // writes are unconditional WalrusDataQueue<WalrusDataMessage> putQueue = messenger.getQueue(key, randomKey); try { WalrusDataMessage dataMessage; String tempObjectName = objectName; MessageDigest digest = null; long size = 0; FileIO fileIO = null; while ((dataMessage = putQueue.take()) != null) { if (putQueue.getInterrupted()) { if (WalrusDataMessage.isEOF(dataMessage)) { WalrusMonitor monitor = messenger.getMonitor(key); if (monitor.getLastModified() == null) { LOG.trace("Monitor wait: " + key + " random: " + randomKey); synchronized (monitor) { monitor.wait(); } } LOG.trace("Monitor resume: " + key + " random: " + randomKey); lastModified = monitor.getLastModified(); md5 = monitor.getMd5(); // ok we are done here if (fileIO != null) { fileIO.finish(); } ObjectDeleter objectDeleter = new ObjectDeleter(bucketName, tempObjectName, null, null, null, -1L, ctx.getUser().getName(), ctx.getUser().getUserId(), ctx.getAccount().getName(), ctx.getAccount().getAccountNumber()); Threads.lookup(WalrusBackend.class, WalrusFSManager.ObjectDeleter.class).limitTo(10) .submit(objectDeleter); LOG.warn("Transfer interrupted: " + key); messenger.removeQueue(key, randomKey); break; } continue; } if (WalrusDataMessage.isStart(dataMessage)) { tempObjectName = UUID.randomUUID().toString(); digest = Digest.MD5.get(); try { fileIO = storageManager.prepareForWrite(bucketName, tempObjectName); } catch (Exception ex) { messenger.removeQueue(key, randomKey); throw new InternalErrorException(ex); } } else if (WalrusDataMessage.isEOF(dataMessage)) { if (digest != null) { md5 = Hashes.bytesToHex(digest.digest()); } else { WalrusMonitor monitor = messenger.getMonitor(key); md5 = monitor.getMd5(); lastModified = monitor.getLastModified(); if (md5 == null) { LOG.error("ETag did not match for: " + randomKey + " Computed MD5 is null"); throw new ContentMismatchException(bucketName + "/" + objectKey); } break; } String contentMD5 = request.getContentMD5(); if (contentMD5 != null) { String contentMD5AsHex = Hashes.bytesToHex(Base64.decode(contentMD5)); if (!contentMD5AsHex.equals(md5)) { if (fileIO != null) { fileIO.finish(); } cleanupTempObject(ctx, bucketName, tempObjectName); messenger.removeQueue(key, randomKey); LOG.error("ETag did not match for: " + randomKey + " Expected: " + contentMD5AsHex + " Computed: " + md5); throw new ContentMismatchException(bucketName + "/" + objectKey); } } // commit object try { if (fileIO != null) { fileIO.finish(); } storageManager.renameObject(bucketName, tempObjectName, objectName); } catch (IOException ex) { LOG.error(ex); messenger.removeQueue(key, randomKey); throw new InternalErrorException(objectKey); } lastModified = new Date(); PartInfo searchPart = new PartInfo(bucketName, objectKey); //objectName is guaranteed to be unique searchPart.setObjectName(objectName); searchPart.setPartNumber(partNumber); searchPart.setUploadId(uploadId); EntityWrapper<PartInfo> dbPart = EntityWrapper.get(PartInfo.class); PartInfo foundPart = null; try { foundPart = dbPart.getUniqueEscape(searchPart); } catch (EucalyptusCloudException ex) { dbPart.rollback(); throw new InternalErrorException("Unable to update part: " + bucketName + "/" + objectKey + " uploadId: " + uploadId + " partNumber: " + partNumber); } foundPart.setEtag(md5); foundPart.setSize(size); foundPart.setLastModified(lastModified); foundPart.setCleanup(false); foundPart.setStorageClass("STANDARD"); reply.setSize(size); try { dbPart.commit(); } catch (RollbackException ex) { dbPart.rollback(); LOG.error(ex, ex); } // restart all interrupted puts WalrusMonitor monitor = messenger.getMonitor(key); synchronized (monitor) { monitor.setLastModified(lastModified); monitor.setMd5(md5); monitor.notifyAll(); } // messenger.removeMonitor(key); messenger.clearQueues(key); messenger.removeQueue(key, randomKey); LOG.trace("Transfer complete: " + key + " uploadId: " + uploadId + " partNumber: " + partNumber); break; } else { assert (WalrusDataMessage.isData(dataMessage)); byte[] data = dataMessage.getPayload(); // start writing object (but do not commit yet) try { if (fileIO != null) fileIO.write(data); } catch (IOException ex) { LOG.error(ex); } // calculate md5 on the fly size += data.length; if (digest != null) { digest.update(data); } } } } catch (Exception ex) { LOG.error(ex, ex); db.rollback(); messenger.removeQueue(key, randomKey); throw new InternalErrorException("Transfer interrupted: " + key + "." + randomKey); } } else { db.rollback(); messenger.removeQueue(key, randomKey); throw new NoSuchBucketException(bucketName); } reply.setEtag(md5); reply.setLastModified(lastModified); return reply; }
From source file:com.eucalyptus.walrus.WalrusFSManager.java
License:Open Source License
public CompleteMultipartUploadResponseType completeMultipartUpload(CompleteMultipartUploadType request) throws WalrusException { CompleteMultipartUploadResponseType reply = (CompleteMultipartUploadResponseType) request.getReply(); Context ctx = Contexts.lookup(); Account account = ctx.getAccount();/*from w ww .j ava 2 s. c o m*/ String bucketName = request.getBucket(); String objectKey = request.getKey(); List<Part> requestParts = request.getParts(); EntityWrapper<BucketInfo> db = EntityWrapper.get(BucketInfo.class); BucketInfo bucketInfo = new BucketInfo(bucketName); List<BucketInfo> bucketList = db.queryEscape(bucketInfo); if (bucketList.size() > 0) { BucketInfo bucket = bucketList.get(0); try { // Find the manifest entity PartInfo searchManifest = new PartInfo(bucketName, objectKey); searchManifest.setUploadId(request.getUploadId()); searchManifest.setCleanup(Boolean.FALSE); EntityWrapper<PartInfo> dbPart = db.recast(PartInfo.class); Criteria partCriteria = dbPart.createCriteria(PartInfo.class); partCriteria.add(Example.create(searchManifest)); partCriteria.add(Restrictions.isNull("partNumber")); List<PartInfo> found = partCriteria.list(); if (found.size() == 0) { db.rollback(); throw new NoSuchUploadException(request.getUploadId()); } if (found.size() > 1) { db.rollback(); throw new InternalErrorException( "Multiple manifests found for same uploadId: " + request.getUploadId()); } PartInfo foundManifest = found.get(0); if (foundManifest != null) { long oldBucketSize = 0L; long oldObjectSize = 0L; //check if we can write to the object if it already exists String versionId = null; if (bucket.isVersioningEnabled()) { versionId = foundManifest.getVersionId(); } else { versionId = WalrusProperties.NULL_VERSION_ID; ObjectInfo searchObject = new ObjectInfo(bucketName, objectKey); searchObject.setVersionId(versionId); EntityWrapper<ObjectInfo> dbObject = db.recast(ObjectInfo.class); try { ObjectInfo foundObject = dbObject.getUniqueEscape(searchObject); if (!foundObject.canWrite(account.getAccountNumber())) { // Found existing object, but don't have write // access db.rollback(); throw new AccessDeniedException("Key", objectKey); } //check if we can write ACP if (foundManifest.getGrants().size() > 0 && (!foundObject.canWriteACP(account.getAccountNumber()))) { db.rollback(); throw new AccessDeniedException("Key", objectKey); } oldObjectSize = foundObject.getSize() == null ? 0L : foundObject.getSize(); // Fix for EUCA-2275: // If an existing object is overwritten, the size // difference must be taken into account. Size of the // already existing object was ignored before oldBucketSize = -oldObjectSize; } catch (AccessDeniedException ex) { throw ex; } catch (EucalyptusCloudException ex) { // No existing object found //empty catch? We need to throw or catch a more specific exception here. EucalyptusCloudException is not //specific enough and could be raised in a variety of cases. } } // Look for the parts PartInfo searchPart = new PartInfo(bucketName, objectKey); searchPart.setUploadId(request.getUploadId()); partCriteria = dbPart.createCriteria(PartInfo.class); partCriteria.add(Example.create(searchManifest)); partCriteria.add(Restrictions.isNotNull("partNumber")); List<PartInfo> foundParts = partCriteria.list(); String eTagString = ""; long size = 0; if (foundParts != null && foundParts.size() > 0) { if (requestParts != null && requestParts.size() > foundParts.size()) { throw new InternalErrorException( "One or more parts has not been uploaded yet. Either upload the part or fix the manifest. Upload Id: " + request.getUploadId()); } else { // Create a hashmap Map<Integer, PartInfo> partsMap = new HashMap<Integer, PartInfo>(foundParts.size()); for (PartInfo foundPart : foundParts) { partsMap.put(foundPart.getPartNumber(), foundPart); } PartInfo lookupPart = null; for (Part requestPart : requestParts) { if ((lookupPart = partsMap.get(requestPart.getPartNumber())) != null) { lookupPart.setCleanup(Boolean.FALSE); eTagString += lookupPart.getEtag(); size += lookupPart.getSize(); partsMap.remove(lookupPart.getPartNumber()); } else { throw new InvalidPartException("Part Number: " + requestPart.getPartNumber() + " upload id: " + request.getUploadId()); } } MessageDigest digest = Digest.MD5.get(); digest.update(eTagString.getBytes()); final String eTag = "uuid-" + Hashes.bytesToHex(digest.digest()); foundManifest.setEtag(eTag); foundManifest.setCleanup(Boolean.FALSE); if (!ctx.hasAdministrativePrivileges() && !Permissions.canAllocate(PolicySpec.VENDOR_S3, PolicySpec.S3_RESOURCE_OBJECT, bucketName, PolicySpec.S3_PUTOBJECT, ctx.getUser(), oldBucketSize + size)) { // dbObject.rollback(); LOG.error("Quota exceeded for WalrusBackend putObject"); throw new EntityTooLargeException("Key", objectKey); } ObjectInfo objectInfo = new ObjectInfo(bucketName, objectKey); objectInfo.setOwnerId(account.getAccountNumber()); objectInfo.setCleanup(false); objectInfo.setEtag(eTag); objectInfo.setUploadId(foundManifest.getUploadId()); objectInfo.setDeleted(false); objectInfo.setSize(size); objectInfo.setLastModified(new Date()); objectInfo.setVersionId(versionId); objectInfo.setStorageClass(foundManifest.getStorageClass()); objectInfo.setContentDisposition(foundManifest.getContentDisposition()); objectInfo.setContentType(foundManifest.getContentType()); objectInfo.setLast(true); objectInfo.setDeleted(false); objectInfo.updateGrants(foundManifest); objectInfo.setMetaData(foundManifest.cloneMetaData()); objectInfo.setLastModified(new Date()); EntityWrapper<ObjectInfo> dbOject = db.recast(ObjectInfo.class); dbOject.add(objectInfo); //cleanup unused parts Set<Integer> keys = partsMap.keySet(); for (Integer key : keys) { partsMap.get(key).markForCleanup(); } db.commit(); reply.setEtag(foundManifest.getEtag()); // TODO figure out etag correctly reply.setLocation("WalrusBackend" + foundManifest.getBucketName() + "/" + foundManifest.getObjectKey()); reply.setBucket(foundManifest.getBucketName()); reply.setKey(foundManifest.getObjectKey()); reply.setLastModified(objectInfo.getLastModified()); //fire cleanup firePartsCleanupTask(foundManifest.getBucketName(), request.getKey(), request.getUploadId()); } } else { throw new InvalidPartException("No parts found for: " + request.getUploadId()); } } else { throw new NoSuchUploadException(request.getUploadId()); } } catch (Exception ex) { db.rollback(); throw new InternalErrorException(ex); } } else { db.rollback(); throw new NoSuchBucketException(bucketName); } reply.setLocation(request.getBucket() + '/' + request.getKey()); reply.setBucket(request.getBucket()); reply.setKey(request.getKey()); return reply; }
From source file:com.eucalyptus.walrus.WalrusFSManager.java
License:Open Source License
public AbortMultipartUploadResponseType abortMultipartUpload(AbortMultipartUploadType request) throws WalrusException { AbortMultipartUploadResponseType reply = (AbortMultipartUploadResponseType) request.getReply(); Context ctx = Contexts.lookup(); Account account = ctx.getAccount();// w w w .ja va 2s . com String bucketName = request.getBucket(); String objectKey = request.getKey(); EntityWrapper<BucketInfo> db = EntityWrapper.get(BucketInfo.class); BucketInfo bucketInfo = new BucketInfo(bucketName); List<BucketInfo> bucketList = db.queryEscape(bucketInfo); if (bucketList.size() > 0) { BucketInfo bucket = bucketList.get(0); try { // Find the manifest entity EntityWrapper<PartInfo> dbPart = db.recast(PartInfo.class); PartInfo searchManifest = new PartInfo(bucketName, objectKey); searchManifest.setUploadId(request.getUploadId()); searchManifest.setCleanup(Boolean.FALSE); Criteria partCriteria = dbPart.createCriteria(PartInfo.class); partCriteria.add(Example.create(searchManifest)); partCriteria.add(Restrictions.isNull("partNumber")); List<PartInfo> found = partCriteria.list(); if (found.size() == 0) { db.rollback(); throw new InternalErrorException( "Multipart upload ID is invalid. Intitiate a multipart upload request before uploading the parts"); } if (found.size() > 1) { db.rollback(); throw new InternalErrorException("Multiple manifests found for same uploadId"); } PartInfo foundManifest = found.get(0); if (foundManifest != null) { // Look for the parts foundManifest.markForCleanup(); PartInfo searchPart = new PartInfo(bucketName, objectKey); searchPart.setUploadId(request.getUploadId()); List<PartInfo> foundParts = dbPart.queryEscape(searchPart); if (foundParts != null && foundParts.size() > 0) { for (PartInfo part : foundParts) { part.markForCleanup(); } } else { throw new InternalErrorException("No parts found for upload: " + request.getUploadId()); } db.commit(); //fire cleanup firePartsCleanupTask(foundManifest.getBucketName(), foundManifest.getObjectKey(), request.getUploadId()); } else { throw new InternalErrorException("Multipart upload ID is invalid."); } } catch (Exception ex) { db.rollback(); throw new InternalErrorException(ex); } } else { db.rollback(); throw new NoSuchBucketException(bucketName); } return reply; }
From source file:com.evolveum.midpoint.repo.sql.query.matcher.Matcher.java
License:Apache License
protected Criterion basicMatch(ItemRestrictionOperation operation, String propertyName, Object value, boolean ignoreCase) throws QueryException { Criterion criterion;/*from w ww . j a v a 2 s. com*/ switch (operation) { case EQ: if (value == null) { criterion = Restrictions.isNull(propertyName); } else { criterion = Restrictions.eq(propertyName, value); } break; case GT: criterion = Restrictions.gt(propertyName, value); break; case GE: criterion = Restrictions.ge(propertyName, value); break; case LT: criterion = Restrictions.lt(propertyName, value); break; case LE: criterion = Restrictions.le(propertyName, value); break; case NOT_NULL: criterion = Restrictions.isNotNull(propertyName); break; case NULL: criterion = Restrictions.isNull(propertyName); break; case STARTS_WITH: criterion = Restrictions.like(propertyName, (String) value, MatchMode.START); break; case ENDS_WITH: criterion = Restrictions.like(propertyName, (String) value, MatchMode.END); break; case SUBSTRING: criterion = Restrictions.like(propertyName, (String) value, MatchMode.ANYWHERE); break; default: throw new QueryException("Unknown operation '" + operation + "'."); } if (ignoreCase && (value instanceof String) && (criterion instanceof SimpleExpression)) { criterion = ((SimpleExpression) criterion).ignoreCase(); } return criterion; }
From source file:com.evolveum.midpoint.repo.sql.query.restriction.ReferenceRestriction.java
License:Apache License
private Criterion handleEqOrNull(String propertyName, Object value) { if (value == null) { return Restrictions.isNull(propertyName); }//from w w w. j a v a 2s. co m return Restrictions.eq(propertyName, value); }
From source file:com.evolveum.midpoint.repo.sql.QueryInterpreterTest.java
License:Apache License
/** * Q{AND: (EQUALS: parent, PPV(null)),PAGING: O: 0,M: 5,BY: name, D:ASCENDING, * * @throws Exception/*from w w w . j av a 2s .c o m*/ */ @Test public void countTaskOrderByName() throws Exception { Session session = open(); try { Criteria main = session.createCriteria(RTask.class, "t"); main.add(Restrictions.isNull("t.parent")); main.setProjection(Projections.rowCount()); String expected = HibernateToSqlTranslator.toSql(main); EqualFilter filter = EqualFilter.createEqual(TaskType.F_PARENT, TaskType.class, prismContext, null); ObjectQuery query = ObjectQuery.createObjectQuery(filter); query.setPaging(ObjectPaging.createPaging(null, null, TaskType.F_NAME, OrderDirection.ASCENDING)); String real = getInterpretedQuery(session, TaskType.class, query, true); LOGGER.info("exp. query>\n{}\nreal query>\n{}", new Object[] { expected, real }); AssertJUnit.assertEquals(expected, real); } finally { close(session); } }
From source file:com.floreantpos.model.dao.MenuCategoryDAO.java
License:Open Source License
public List<MenuCategory> findNonBevegares() { Session session = null;/* w w w .j a va2s.c om*/ try { session = getSession(); Criteria criteria = session.createCriteria(getReferenceClass()); criteria.add(Restrictions.eq(MenuCategory.PROP_VISIBLE, Boolean.TRUE)); criteria.add(Restrictions.or(Restrictions.isNull(MenuCategory.PROP_BEVERAGE), Restrictions.eq(MenuCategory.PROP_BEVERAGE, Boolean.FALSE))); return criteria.list(); } finally { closeSession(session); } }