List of usage examples for org.hibernate.criterion Restrictions le
public static SimpleExpression le(String propertyName, Object value)
From source file:com.duroty.application.mail.manager.MailManager.java
License:Open Source License
/** * DOCUMENT ME!//from w w w . j av a 2 s. com * * @param hsession DOCUMENT ME! * @param user DOCUMENT ME! * @param mid DOCUMENT ME! * @param midReferences DOCUMENT ME! * @param date DOCUMENT ME! * @param beforeSent DOCUMENT ME! * @param isHtml DOCUMENT ME! * * @return DOCUMENT ME! */ private Vector readReference(Session hsession, Users user, String mid, String midReferences, Date date1, boolean beforeSent, boolean isHtml, boolean displayImages) { Vector references = new Vector(); ByteArrayOutputStream baos = null; try { Locale locale = new Locale(user.getUseLanguage()); TimeZone timeZone = TimeZone.getDefault(); Date now = new Date(); Calendar calendar = Calendar.getInstance(timeZone, locale); calendar.setTime(now); SimpleDateFormat formatter1 = new SimpleDateFormat("MMM dd", locale); SimpleDateFormat formatter2 = new SimpleDateFormat("HH:mm:ss", locale); SimpleDateFormat formatter3 = new SimpleDateFormat("MM/yy", locale); Criteria crit = hsession.createCriteria(Message.class); crit.add(Restrictions.not(Restrictions.eq("mesName", mid))); crit.add(Restrictions.eq("mesReferences", midReferences)); crit.add(Restrictions.eq("users", user)); crit.add(Restrictions.not(Restrictions.eq("mesBox", this.folderSpam))); crit.add(Restrictions.not(Restrictions.eq("mesBox", this.folderTrash))); crit.add(Restrictions.not(Restrictions.eq("mesBox", FOLDER_DELETE))); if (beforeSent) { crit.add(Restrictions.le("mesDate", date1)); } else { crit.add(Restrictions.gt("mesDate", date1)); } crit.addOrder(Order.asc("mesDate")); ScrollableResults scroll = crit.scroll(); while (scroll.next()) { Message message = (Message) scroll.get(0); message.setMesRecent(false); hsession.update(message); hsession.flush(); MessageObj obj = new MessageObj(message.getMesName()); obj.setBox(message.getMesBox()); obj.setFrom(message.getMesFrom()); obj.setTo(message.getMesTo()); obj.setReplyTo(message.getMesReplyTo()); obj.setCc(message.getMesCc()); if ((message.getAttachments() != null) && (message.getAttachments().size() > 0)) { obj.setHasAttachment(true); Set set = message.getAttachments(); Iterator it = set.iterator(); Vector attachments = new Vector(); while (it.hasNext()) { Attachment attachment = (Attachment) it.next(); AttachmentObj attachmentObj = new AttachmentObj(); attachmentObj.setIdint(attachment.getAttPart()); attachmentObj.setName(attachment.getAttName()); int size = attachment.getAttSize(); size /= 1024; if (size > 1024) { size /= 1024; attachmentObj.setSize(size + " MB"); } else { attachmentObj.setSize(((size > 0) ? (size + "") : "<1") + " kB"); } String extension = (String) this.extensions.get(attachment.getAttContentType()); if (StringUtils.isBlank(extension)) { extension = "generic"; } attachmentObj.setExtension(extension); attachmentObj.setContentType(attachment.getAttContentType()); attachments.addElement(attachmentObj); obj.setAttachments(attachments); } } else { obj.setHasAttachment(false); } int size = message.getMesSize(); size /= 1024; if (size > 1024) { size /= 1024; obj.setSize(size + " MB"); } else { obj.setSize(((size > 0) ? (size + "") : "<1") + " kB"); } if (message.getMesBox().equals(folderSent)) { try { obj.setEmail(message.getMesTo()); } catch (Exception e) { obj.setEmail("unknown to"); } } else { obj.setEmail(message.getMesFrom()); } Date date = message.getMesDate(); if (date != null) { Calendar calendar2 = Calendar.getInstance(timeZone, locale); calendar2.setTime(date); if ((calendar.get(Calendar.YEAR) == calendar2.get(Calendar.YEAR)) && (calendar.get(Calendar.MONTH) == calendar2.get(Calendar.MONTH)) && (calendar.get(Calendar.DATE) == calendar2.get(Calendar.DATE))) { obj.setDateStr(formatter2.format(calendar2.getTime())); } else if (calendar.get(Calendar.YEAR) == calendar2.get(Calendar.YEAR)) { obj.setDateStr(formatter1.format(calendar2.getTime())); } else { obj.setDateStr(formatter3.format(calendar2.getTime())); } } obj.setDate(date); if (message.getLabMeses() != null) { Iterator it = message.getLabMeses().iterator(); StringBuffer label = new StringBuffer(); while (it.hasNext()) { if (label.length() > 0) { label.append(", "); } LabMes labMes = (LabMes) it.next(); label.append(labMes.getId().getLabel().getLabName()); } obj.setLabel(label.toString()); } try { if (StringUtils.isBlank(message.getMesSubject())) { obj.setSubject("(no subject)"); } else { obj.setSubject(message.getMesSubject()); } } catch (Exception ex) { obj.setSubject("(no subject)"); } if (message.isMesFlagged()) { obj.setFlagged(true); } else { obj.setFlagged(false); } if (message.isMesRecent()) { obj.setRecent(true); } else { obj.setRecent(false); } String priority = "normal"; if (MessageUtilities.isHighPriority(message.getMesHeaders())) { priority = "high"; } else if (MessageUtilities.isLowPriority(message.getMesHeaders())) { priority = "low"; } obj.setPriority(priority); String body = message.getMesBody(); if (!StringUtils.isBlank(body)) { obj.setBody(bodyCleaner(body, displayImages)); } else { obj.setBody(""); } references.addElement(obj); } scroll.close(); } catch (Exception ex) { return null; } finally { IOUtils.closeQuietly(baos); } if (references.size() <= 0) { return null; } return references; }
From source file:com.duroty.task.ChatConversationsTask.java
License:Open Source License
/** * DOCUMENT ME!/* w w w. ja v a2s .co m*/ * * @param dirUsers DOCUMENT ME! * * @throws Exception DOCUMENT ME! */ public void flush() throws Exception { SessionFactory hfactory = null; Session hsession = null; try { hfactory = (SessionFactory) ctx.lookup(hibernateSessionFactory); hsession = hfactory.openSession(); Calendar cal = new GregorianCalendar(); //int hour = cal.get(Calendar.HOUR_OF_DAY); //int minute = cal.get(Calendar.MINUTE); //int second = cal.get(Calendar.SECOND); Calendar cal1 = new GregorianCalendar(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE) - 1, cal.get(Calendar.SECOND)); Date date = new Date(cal1.getTimeInMillis()); Criteria crit = hsession.createCriteria(Conversations.class); crit.add(Restrictions.le("convStamp", date)); crit.addOrder(Order.asc("convStamp")); ScrollableResults scroll = crit.scroll(); while (scroll.next()) { hsession.delete(scroll.get(0)); hsession.flush(); } } catch (Exception e) { System.gc(); StringWriter writer = new StringWriter(); e.printStackTrace(new PrintWriter(writer)); DLog.log(DLog.ERROR, this.getClass(), writer.toString()); } catch (OutOfMemoryError e) { System.gc(); StringWriter writer = new StringWriter(); e.printStackTrace(new PrintWriter(writer)); DLog.log(DLog.ERROR, this.getClass(), writer.toString()); } catch (Throwable e) { System.gc(); StringWriter writer = new StringWriter(); e.printStackTrace(new PrintWriter(writer)); DLog.log(DLog.ERROR, this.getClass(), writer.toString()); } finally { GeneralOperations.closeHibernateSession(hsession); setInit(false); System.gc(); } }
From source file:com.duroty.task.ChatTask.java
License:Open Source License
/** * DOCUMENT ME!/*from www . j ava2 s . c o m*/ * * @param dirUsers DOCUMENT ME! * * @throws Exception DOCUMENT ME! */ public void flush() throws Exception { SessionFactory hfactory = null; Session hsession = null; try { hfactory = (SessionFactory) ctx.lookup(hibernateSessionFactory); hsession = hfactory.openSession(); Calendar cal = new GregorianCalendar(); //int hour = cal.get(Calendar.HOUR_OF_DAY); //int minute = cal.get(Calendar.MINUTE); //int second = cal.get(Calendar.SECOND); Calendar cal1 = new GregorianCalendar(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE) - 5, cal.get(Calendar.SECOND)); Date date = new Date(cal1.getTimeInMillis()); Criteria crit = hsession.createCriteria(Users.class); crit.add(Restrictions.le("useLastPing", date)); crit.add(Restrictions.not(Restrictions.eq("useIsOnline", new Integer(0)))); crit.add(Restrictions.isNotNull("useIsOnline")); ScrollableResults scroll = crit.scroll(); while (scroll.next()) { Users user = (Users) scroll.get(0); user.setUseIsOnline(0); hsession.update(user); hsession.flush(); } /*cal1 = new GregorianCalendar(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE) - 1, cal.get(Calendar.SECOND)); date = new Date(cal1.getTimeInMillis()); crit = hsession.createCriteria(Conversations.class); crit.add(Restrictions.le("convStamp", date)); scroll = crit.scroll(); while (scroll.next()) { Conversations conv = (Conversations) scroll.get(0); hsession.update(conv); hsession.flush(); }*/ } catch (Exception e) { System.gc(); StringWriter writer = new StringWriter(); e.printStackTrace(new PrintWriter(writer)); DLog.log(DLog.ERROR, this.getClass(), writer.toString()); } catch (OutOfMemoryError e) { System.gc(); StringWriter writer = new StringWriter(); e.printStackTrace(new PrintWriter(writer)); DLog.log(DLog.ERROR, this.getClass(), writer.toString()); } catch (Throwable e) { System.gc(); StringWriter writer = new StringWriter(); e.printStackTrace(new PrintWriter(writer)); DLog.log(DLog.ERROR, this.getClass(), writer.toString()); } finally { GeneralOperations.closeHibernateSession(hsession); setInit(false); System.gc(); } }
From source file:com.duroty.task.PurgeTrashAndSpam.java
License:Open Source License
/** * DOCUMENT ME!/* w w w. j a v a2 s .c o m*/ */ private void flush() { setInit(true); SessionFactory hfactory = null; Session hsession = null; try { hfactory = (SessionFactory) ctx.lookup(hibernateSessionFactory); hsession = hfactory.openSession(); Calendar cal = new GregorianCalendar(); int year = cal.get(Calendar.YEAR); // 2002 int month = cal.get(Calendar.MONTH); // 0=Jan, 1=Feb, ... int day = cal.get(Calendar.DAY_OF_MONTH); // 1... Calendar cal1 = new GregorianCalendar(year, month - 1, day, 0, 0, 0); Date date = new Date(cal1.getTimeInMillis()); Criteria criteria = hsession.createCriteria(Message.class); criteria.add(Restrictions.in("mesBox", new String[] { this.folderSpam, this.folderTrash })); criteria.add(Restrictions.le("mesDate", date)); criteria.addOrder(Order.asc("mesDate")); ScrollableResults scroll = criteria.scroll(); while (scroll.next()) { Message message = (Message) scroll.get(0); Users user = message.getUsers(); try { messageable.deleteMimeMessage(message.getMesName(), user); } catch (Exception e) { DLog.log(DLog.INFO, this.getClass(), e.getMessage() + " for user " + user.getUseUsername()); } hsession.delete(message); hsession.flush(); Thread.sleep(100); } } catch (Exception e) { System.gc(); DLog.log(DLog.WARN, this.getClass(), e.getMessage()); } catch (OutOfMemoryError e) { System.gc(); DLog.log(DLog.WARN, this.getClass(), e.getMessage()); } catch (Throwable e) { System.gc(); DLog.log(DLog.WARN, this.getClass(), e.getMessage()); } finally { GeneralOperations.closeHibernateSession(hsession); setInit(false); } }
From source file:com.eharmony.matching.seeking.translator.hibernate.HibernateQueryTranslator.java
License:Apache License
@Override public Criterion lte(String fieldName, Object value) { return Restrictions.le(fieldName, value); }
From source file:com.eryansky.common.orm.core.hibernate.restriction.support.LeRestriction.java
License:Apache License
public Criterion build(String propertyName, Object value) { return Restrictions.le(propertyName, value); }
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 www . j a va2 s.co 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.cloudwatch.common.internal.domain.alarms.AlarmManager.java
License:Open Source License
public static List<AlarmHistory> describeAlarmHistory(@Nullable final String accountId, @Nullable final String alarmName, @Nullable final Date endDate, @Nullable final HistoryItemType historyItemType, @Nullable final Integer maxRecords, @Nullable final Date startDate, @Nullable final String nextToken, final Predicate<AlarmHistory> filter) throws InvalidTokenException { final List<AlarmHistory> results = Lists.newArrayList(); try (final TransactionResource db = Entities.transactionFor(AlarmHistory.class)) { final Map<String, Collection<String>> accountToNamesMap = alarmName == null ? Collections.<String, Collection<String>>emptyMap() : buildAccountIdToAlarmNamesMap(accountId, Collections.singleton(alarmName)); boolean first = true; String token = nextToken; while (token != null || first) { first = false;//w w w . j av a 2 s. c o m final Date nextTokenCreatedTime = NextTokenUtils.getNextTokenCreatedTime(token, AlarmHistory.class); final Criteria criteria = Entities.createCriteria(AlarmHistory.class); final Junction disjunction = Restrictions.disjunction(); for (final Map.Entry<String, Collection<String>> entry : accountToNamesMap.entrySet()) { final Junction conjunction = Restrictions.conjunction(); conjunction.add(Restrictions.eq("accountId", entry.getKey())); conjunction.add(Restrictions.in("alarmName", entry.getValue())); disjunction.add(conjunction); } criteria.add(disjunction); if (historyItemType != null) { criteria.add(Restrictions.eq("historyItemType", historyItemType)); } if (startDate != null) { criteria.add(Restrictions.ge("timestamp", startDate)); } if (endDate != null) { criteria.add(Restrictions.le("timestamp", endDate)); } NextTokenUtils.addNextTokenConstraints(maxRecords == null ? null : maxRecords - results.size(), token, nextTokenCreatedTime, criteria); final List<AlarmHistory> alarmHistoryEntities = (List<AlarmHistory>) criteria.list(); Iterables.addAll(results, Iterables.filter(alarmHistoryEntities, filter)); token = maxRecords == null || (maxRecords != null && (results.size() >= maxRecords || alarmHistoryEntities.size() < maxRecords)) ? null : alarmHistoryEntities.get(alarmHistoryEntities.size() - 1).getNaturalId(); } db.commit(); } return results; }
From source file:com.eucalyptus.cloudwatch.common.internal.domain.listmetrics.ListMetricManager.java
License:Open Source License
/** * Returns the metrics that are associated with the applied parameters * @param accountId the account Id. If null, this filter will not be used. * @param metricName the metric name. If null, this filter will not be used. * @param namespace the namespace. If null, this filter will not be used. * @param dimensionMap the dimensions (name/value) to filter against. Only metrics containing all these dimensions will be returned (it is only a subset match, not exact). If null, this filter will not be used. * @param after the time after which all metrics must have been updated (last seen). If null, this filter will not be used. * @param before the time before which all metrics must have been updated (last seen). If null, this filter will not be used. * @param maxRecords TODO/*www . j a va 2 s . c om*/ * @param nextToken TODO * @return the collection of metrics, filtered by the input */ public static List<ListMetric> listMetrics(String accountId, String metricName, String namespace, Map<String, String> dimensionMap, Date after, Date before, Integer maxRecords, String nextToken) throws InvalidTokenException { if (dimensionMap != null && dimensionMap.size() > ListMetric.MAX_DIM_NUM) { throw new IllegalArgumentException("Too many dimensions " + dimensionMap.size()); } try (final TransactionResource db = Entities.transactionFor(ListMetric.class)) { Date nextTokenCreatedTime = NextTokenUtils.getNextTokenCreatedTime(nextToken, ListMetric.class); Map<String, String> sortedDimensionMap = new TreeMap<String, String>(); Criteria criteria = Entities.createCriteria(ListMetric.class); if (accountId != null) { criteria = criteria.add(Restrictions.eq("accountId", accountId)); } if (metricName != null) { criteria = criteria.add(Restrictions.eq("metricName", metricName)); } if (namespace != null) { criteria = criteria.add(Restrictions.eq("namespace", namespace)); } if (before != null) { criteria = criteria.add(Restrictions.le("lastUpdateTimestamp", before)); } if (after != null) { criteria = criteria.add(Restrictions.ge("lastUpdateTimestamp", after)); } if (dimensionMap != null && !dimensionMap.isEmpty()) { // sort the map sortedDimensionMap.putAll(dimensionMap); // now we are going to add a bunch of restrictions to the criteria... // note though there are certain dimensions we don't need to check. // For example if we have two dimensions, we don't need to check dimension 10 for // the first item or dimension 1 for the last item. int numDimensions = sortedDimensionMap.size(); int lowDimNum = 1; int highDimNum = ListMetric.MAX_DIM_NUM + 1 - numDimensions; for (Map.Entry<String, String> dimEntry : sortedDimensionMap.entrySet()) { Disjunction or = Restrictions.disjunction(); for (int i = lowDimNum; i <= highDimNum; i++) { or.add(Restrictions.conjunction() .add(Restrictions.eq("dim" + i + "Name", dimEntry.getKey())) .add(Restrictions.eq("dim" + i + "Value", dimEntry.getValue()))); } lowDimNum++; highDimNum++; criteria = criteria.add(or); } } criteria = NextTokenUtils.addNextTokenConstraints(maxRecords, nextToken, nextTokenCreatedTime, criteria); List<ListMetric> dbResult = (List<ListMetric>) criteria.list(); db.commit(); return dbResult; } }
From source file:com.eucalyptus.cloudwatch.domain.alarms.AlarmManager.java
License:Open Source License
public static List<AlarmHistory> describeAlarmHistory(@Nullable final String accountId, @Nullable final String alarmName, @Nullable final Date endDate, @Nullable final HistoryItemType historyItemType, @Nullable final Integer maxRecords, @Nullable final Date startDate, @Nullable final String nextToken, final Predicate<AlarmHistory> filter) throws CloudWatchException { final List<AlarmHistory> results = Lists.newArrayList(); final EntityTransaction db = Entities.get(AlarmHistory.class); try {/*from ww w . j a v a 2s . co m*/ final Map<String, Collection<String>> accountToNamesMap = alarmName == null ? Collections.<String, Collection<String>>emptyMap() : buildAccountIdToAlarmNamesMap(accountId, Collections.singleton(alarmName)); boolean first = true; String token = nextToken; while (token != null || first) { first = false; final Date nextTokenCreatedTime = NextTokenUtils.getNextTokenCreatedTime(token, AlarmHistory.class, true); final Criteria criteria = Entities.createCriteria(AlarmHistory.class); final Junction disjunction = Restrictions.disjunction(); for (final Map.Entry<String, Collection<String>> entry : accountToNamesMap.entrySet()) { final Junction conjunction = Restrictions.conjunction(); conjunction.add(Restrictions.eq("accountId", entry.getKey())); conjunction.add(Restrictions.in("alarmName", entry.getValue())); disjunction.add(conjunction); } criteria.add(disjunction); if (historyItemType != null) { criteria.add(Restrictions.eq("historyItemType", historyItemType)); } if (startDate != null) { criteria.add(Restrictions.ge("timestamp", startDate)); } if (endDate != null) { criteria.add(Restrictions.le("timestamp", endDate)); } NextTokenUtils.addNextTokenConstraints(maxRecords == null ? null : maxRecords - results.size(), token, nextTokenCreatedTime, criteria); final List<AlarmHistory> alarmHistoryEntities = (List<AlarmHistory>) criteria.list(); Iterables.addAll(results, Iterables.filter(alarmHistoryEntities, filter)); token = maxRecords == null || (maxRecords != null && (results.size() >= maxRecords || alarmHistoryEntities.size() < maxRecords)) ? null : alarmHistoryEntities.get(alarmHistoryEntities.size() - 1).getNaturalId(); } db.commit(); } catch (RuntimeException ex) { Logs.extreme().error(ex, ex); throw ex; } finally { if (db.isActive()) db.rollback(); } return results; }