List of usage examples for org.hibernate Query setTimestamp
@Deprecated @SuppressWarnings("unchecked") default Query<R> setTimestamp(String name, Date value)
From source file:gov.nih.nci.objectCart.dao.orm.CleanerDAO.java
License:BSD License
public void clean() { if (sessionFactory == null) { setFactory();//www .j av a 2 s . c o m this.setSessionFactory(sessionFactory); } Session session = getSession(); Transaction tx = session.beginTransaction(); //Check for unexpired carts that have been active within the expiration interval and reset expiration time. int expirationInterval = 4 * 24 * 60; //Four days, in minutes int sleepTime = 60; //One hour, in minutes //Defaults int publicEmptyExpirationDays = 4 * 24 * 60; String emptyExpirationSQL = "DATE_ADD(NOW(), INTERVAL " + publicEmptyExpirationDays + " MINUTE)"; int publicFullExpirationDays = 30 * 24 * 60; //30 days, in minutes String fullExpirationSQL = "DATE_ADD(NOW(), INTERVAL " + publicFullExpirationDays + " MINUTE)"; try { int temp = Integer.valueOf(PropertiesLoader.getProperty("cart.time.expiration.minutes")); expirationInterval = temp; } catch (Exception e) { log.error(e); } try { int temp = Integer.valueOf(PropertiesLoader.getProperty("cart.cleaner.sleep.minutes")); sleepTime = temp; } catch (Exception e) { log.error(e); } try { int temp = Integer.valueOf(PropertiesLoader.getProperty("cart.public.empty.expiration.minutes")); publicEmptyExpirationDays = temp; } catch (Exception e) { log.error(e); } try { int temp = Integer.valueOf(PropertiesLoader.getProperty("cart.public.full.expiration.minutes")); publicFullExpirationDays = temp; } catch (Exception e) { log.error(e); } //Timestamps are in milliseconds Timestamp now = new Timestamp(System.currentTimeMillis()); Timestamp nowMinusTwiceSleep = new Timestamp(now.getTime() - sleepTime * 60 * 1000 * 2); //Converting minutes to milliseconds Timestamp nowPlusExpirationInterval = new Timestamp(now.getTime() + expirationInterval * 60 * 1000); //Converting minutes to milliseconds Query updateActiveCarts = session.createQuery("update Cart set expirationDate = :nowPlusExpirationInterval" + " where (lastWriteDate > :nowMinusTwiceSleep or lastReadDate > :nowMinusTwiceSleep) and expirationDate > :now and expirationDate < :nowPlusExpirationInterval"); updateActiveCarts.setTimestamp("nowPlusExpirationInterval", nowPlusExpirationInterval); updateActiveCarts.setTimestamp("nowMinusTwiceSleep", nowMinusTwiceSleep); updateActiveCarts.setTimestamp("now", now); if (publicEmptyExpirationDays > 0 && publicEmptyExpirationDays < 365 * 24 * 60) //Check expiration is within a year emptyExpirationSQL = "DATE_ADD(NOW(), INTERVAL " + publicEmptyExpirationDays + " MINUTE)"; else if (publicEmptyExpirationDays == 0) emptyExpirationSQL = "NOW()"; if (publicFullExpirationDays > 0 && publicFullExpirationDays < 365) //Check expiration is within a year fullExpirationSQL = "DATE_ADD(NOW(), INTERVAL " + publicFullExpirationDays + " MINUTE)"; else if (publicFullExpirationDays == 0) fullExpirationSQL = "NOW()"; //Set expiration date to emptyExpirationSQL if the user starts with 'PublicUser' and the current expiration date is null String initializeSessionCartSql = "UPDATE cart c" + " set expiration_Date = " + emptyExpirationSQL + " where" + " (c.user_Id like 'PublicUser%') and " + " (c.expiration_Date is null)"; Query initPublicCarts = session.createSQLQuery(initializeSessionCartSql); //Set expiration date to fullExpiration if the user starts with 'PublicUser', the cart has been active (read or written to) in the last day and the cart has items String nonEmptyCartSql = "UPDATE cart c left join cart_object co on c.id = co.cart_id " + " set expiration_Date = " + fullExpirationSQL + " where" + " (c.user_Id like 'PublicUser%') and " + " (c.last_write_date > DATE_SUB(NOW(), INTERVAL " + (sleepTime * 2) + " MINUTE) OR c.last_read_date > DATE_SUB(NOW(), INTERVAL " + (sleepTime * 2) + " MINUTE)) and" + " (co.id is not null)"; Query expNonEmptyPublicCarts = session.createSQLQuery(nonEmptyCartSql); //Now delete expired carts (carts where expiration date is in the past) //REQUIRES ON-DELETE Cascade support in underlying database on the //CartObject cart_id FK constraint Query deleteCartQuery = session.createQuery("delete from Cart " + "where expirationDate <=:now"); deleteCartQuery.setTimestamp("now", now); try { int resetResults = updateActiveCarts.executeUpdate(); if (resetResults > 0) log.debug("Reset expiration date for " + resetResults + "active carts"); log.debug("Reset expiration date for " + resetResults + "active carts"); /* GF 28500 */ int expResults = initPublicCarts.executeUpdate(); if (expResults > 0) log.debug("Expiration date set for " + expResults + " PublicUser carts"); int expNEPCResults = expNonEmptyPublicCarts.executeUpdate(); if (expNEPCResults > 0) log.debug("Expiration date set for " + expNEPCResults + " PublicUser carts"); /* GF 28500 */ int results = deleteCartQuery.executeUpdate(); if (results > 0) log.debug("Deleted " + results + " carts at " + now.toString()); } catch (JDBCException ex) { log.error("JDBC Exception in ORMDAOImpl ", ex); ex.printStackTrace(); } catch (org.hibernate.HibernateException hbmEx) { log.error(hbmEx.getMessage()); hbmEx.printStackTrace(); } catch (Exception e) { log.error("Exception ", e); e.printStackTrace(); } finally { try { tx.commit(); session.close(); } catch (Exception eSession) { log.error("Could not close the session - " + eSession.getMessage()); eSession.printStackTrace(); } } }
From source file:it.eng.spagobi.kpi.config.dao.KpiDAOImpl.java
License:Mozilla Public License
public JSONObject getKpiTrendJSONResult(Integer kpiInstId, Date beginDate, Date endDate) throws SourceBeanException { logger.debug("IN"); JSONObject toReturn = new JSONObject(); int numRows = 0; Session aSession = null;//from w ww .j a v a 2 s . c om Transaction tx = null; try { aSession = getSession(); tx = aSession.beginTransaction(); String hql = "select max(s.idKpiInstanceValue), s.beginDt"; hql += " from SbiKpiValue s where s.sbiKpiInstance.idKpiInstance = ? "; hql += " and s.beginDt <= ? and s.beginDt >= ? "; hql += "group by s.beginDt order by s.beginDt desc"; Query hqlQuery = aSession.createQuery(hql); hqlQuery.setInteger(0, kpiInstId); //hqlQuery.setDate(1, endDate); //hqlQuery.setDate(2, beginDate); hqlQuery.setTimestamp(1, endDate); hqlQuery.setTimestamp(2, beginDate); //hqlQuery.setMaxResults(10); List l = hqlQuery.list(); JSONArray jsonData = new JSONArray(); if (!l.isEmpty()) { logger.debug("The result list is not empty"); for (int k = l.size() - 1; k >= 0; k--) { Object[] tempL = (Object[]) l.get(k); JSONObject jsonObj = new JSONObject(); Integer kpiValueId = (Integer) tempL[0]; SbiKpiValue temp = (SbiKpiValue) aSession.load(SbiKpiValue.class, kpiValueId); if (temp != null && temp.getValue() != null) { try { numRows++; Date dt = temp.getBeginDt(); SimpleDateFormat sdf; sdf = new SimpleDateFormat("d"); String day = sdf.format(dt); sdf = new SimpleDateFormat("MM"); String month = sdf.format(dt); sdf = new SimpleDateFormat("yyyy"); String year = sdf.format(dt); sdf = new SimpleDateFormat("H"); String hour = sdf.format(dt); sdf = new SimpleDateFormat("m"); String min = sdf.format(dt); sdf = new SimpleDateFormat("s"); String sec = sdf.format(dt); String format = GeneralUtilities.getServerTimeStampFormat(); String strDtReturn = day + "/" + month + "/" + year + " " + hour + ":" + min + ":" + sec; sdf = new SimpleDateFormat(format); Float valueReturn = Float.parseFloat(temp.getValue()); logger.debug("Date for KPI : " + dt); logger.debug("Value of KPI: " + valueReturn); jsonObj.put("id", k + 1); jsonObj.put("KPI_DATE", strDtReturn); //KPI_DATE jsonObj.put("KPI_VALUE", valueReturn); //KPI_VALUE jsonData.put(jsonObj); } catch (Exception e) { logger.error("Error while getting trend data", e); return null; } } } } toReturn = new JSONObject(); toReturn.put("trends", jsonData); } catch (HibernateException he) { if (tx != null) tx.rollback(); logger.error(he); } catch (Exception e) { logger.error("Error while getting trend data", e); return null; } finally { if (aSession != null) { if (aSession.isOpen()) aSession.close(); logger.debug("OUT"); } } return toReturn; }
From source file:it.eng.spagobi.kpi.config.dao.KpiDAOImpl.java
License:Mozilla Public License
public Integer getKpiTrend(Integer resId, Integer kpiInstId, Date endDate) throws Exception { logger.debug("IN"); Integer toReturn = null;/*from w ww . j a v a2s .c om*/ Session aSession = null; Transaction tx = null; try { aSession = getSession(); tx = aSession.beginTransaction(); String hql = "select max(s.idKpiInstanceValue), s.value, s.beginDt"; hql += " from SbiKpiValue s where s.sbiKpiInstance.idKpiInstance = ? "; hql += " and s.beginDt <= ? "; //hql += " and s.endDt > ? "; if (resId != null) { hql += " and s.sbiResources.resourceId = ? "; } else { logger.debug("Null resource setted"); } hql += "group by s.beginDt order by s.beginDt desc"; Query hqlQuery = aSession.createQuery(hql); hqlQuery.setInteger(0, kpiInstId); hqlQuery.setTimestamp(1, endDate); //hqlQuery.setTimestamp(2, endDate); if (resId != null) { hqlQuery.setInteger(3, resId); logger.debug("Resource setted"); } else { logger.debug("Null resource setted"); } hqlQuery.setMaxResults(2); List l = hqlQuery.list(); Double lastValue = null; Double previousValue = null; if (!l.isEmpty()) { logger.debug("The result list is not empty"); //for (int k = l.size() - 1; k >= 0; k--) { for (int k = 0; k < l.size(); k++) { Object[] tempL = (Object[]) l.get(k); Integer kpiValueId = (Integer) tempL[0]; //SbiKpiValue temp = (SbiKpiValue) aSession.load(SbiKpiValue.class, kpiValueId); String tempVal = (String) tempL[1]; if (tempVal != null) { if (lastValue == null) { lastValue = Double.parseDouble(tempVal); } else { previousValue = Double.parseDouble(tempVal); } } } if (previousValue == null) { return null; } else { logger.debug(lastValue + " " + previousValue); if (lastValue != null && lastValue != null && previousValue != null && previousValue != null) { if (lastValue > previousValue) { toReturn = 1; } else if (lastValue < previousValue) { toReturn = -1; } else { toReturn = 0; } } } } else { logger.debug("The result list is empty"); } } catch (HibernateException he) { if (tx != null) tx.rollback(); logger.error(he); } finally { if (aSession != null) { if (aSession.isOpen()) aSession.close(); logger.debug("OUT"); } } return toReturn; }
From source file:it.eng.spagobi.monitoring.dao.DbAuditImpl.java
License:Mozilla Public License
public SbiAudit getLastExecution(Integer objId) throws EMFUserError { logger.debug("IN"); Session aSession = null;/* w w w. j a va 2 s. co m*/ Transaction tx = null; SbiAudit toReturn = new SbiAudit(); if (objId == null) { logger.warn("The object id in input is null or empty."); return toReturn; } try { aSession = getSession(); tx = aSession.beginTransaction(); StringBuffer hql = new StringBuffer(); hql.append("select "); hql.append(" max(a.executionStartTime)"); hql.append("from "); hql.append(" SbiAudit a "); hql.append("where "); hql.append(" a.sbiObject is not null and "); hql.append(" a.sbiObject.biobjId = ? "); Query hqlQuery = aSession.createQuery(hql.toString()); hqlQuery.setInteger(0, objId.intValue()); Timestamp date = (Timestamp) hqlQuery.uniqueResult(); toReturn.setDocumentId(objId); toReturn.setExecutionStartTime(date); StringBuffer hql2 = new StringBuffer(); hql2.append("select "); hql2.append(" a.userName, "); hql2.append(" a.documentParameters, "); hql2.append(" a.requestTime, "); hql2.append(" a.executionEndTime, "); hql2.append(" a.executionState "); hql2.append("from "); hql2.append(" SbiAudit a "); hql2.append("where "); hql2.append(" a.sbiObject is not null and "); hql2.append(" a.sbiObject.biobjId = ? and "); hql2.append(" a.executionStartTime = ? "); Query hqlQuery2 = aSession.createQuery(hql2.toString()); hqlQuery2.setInteger(0, objId.intValue()); hqlQuery2.setTimestamp(1, date); Object[] row = (Object[]) hqlQuery2.uniqueResult(); toReturn.setUserName((String) row[0]); toReturn.setDocumentParameters((String) row[1]); toReturn.setRequestTime((Timestamp) row[2]); toReturn.setExecutionEndTime((Timestamp) row[3]); toReturn.setExecutionState((String) row[4]); } catch (Exception ex) { logger.error(ex); if (tx != null) tx.rollback(); throw new EMFUserError(EMFErrorSeverity.ERROR, 100); } finally { if (aSession != null) { if (aSession.isOpen()) aSession.close(); } logger.debug("OUT"); } return toReturn; }
From source file:itensil.workflow.activities.state.ActivityStateStore.java
License:Open Source License
@SuppressWarnings("unchecked") public Collection<StepLog<Activity>> getLogSteps(Activity token, Date since) throws StateException { Query qry = getSession().getNamedQuery("FlowState.getLogStepsByToken"); qry.setEntity("token", token); qry.setTimestamp("since", since); return qry.list(); }
From source file:itensil.workflow.activities.state.ActivityStateStore.java
License:Open Source License
@SuppressWarnings("unchecked") public Collection<StepLog<Activity>> getLogSteps(String stepId, Date since) throws StateException { Query qry = getSession().getNamedQuery("FlowState.getLogStepsByStep"); qry.setEntity("flow", getFlow()); qry.setString("stepId", stepId); qry.setTimestamp("since", since); return qry.list(); }
From source file:itensil.workflow.activities.state.ActivityStateStore.java
License:Open Source License
@SuppressWarnings("unchecked") public Collection<StepLog<Activity>> getLogSteps(Date since) throws StateException { Query qry = getSession().getNamedQuery("FlowState.getLogSteps"); qry.setEntity("flow", getFlow()); qry.setTimestamp("since", since); return qry.list(); }
From source file:itensil.workflow.activities.timer.TimerDaemon.java
License:Open Source License
@SuppressWarnings("unchecked") public void run() { log.info("Started"); try {//from w w w. j a v a 2 s .com // query for next timer HibernateUtil.beginTransaction(); HibernateUtil.readOnlySession(); Query qry = HibernateUtil.getSession().getNamedQuery("Timer.getNextTimer"); qry.setMaxResults(1); Iterator<ActivityTimer> atItr = qry.iterate(); ActivityTimer nxtActTimer = atItr.hasNext() ? atItr.next() : null; nextTimer = nxtActTimer != null ? nxtActTimer.getAtTime() : null; HibernateUtil.commitTransaction(); HibernateUtil.closeSession(); // super user thread SecurityAssociation.setUser(SysAdmin.getUser()); } catch (Exception ex) { log.error(ex); // try attmept in 3 minutes, DB is probably down nextTimer = new Date(System.currentTimeMillis() + 3 * 60000); } // main loop while (keepRunning) { try { // check on next timer if (nextTimer != null && nextTimer.getTime() <= System.currentTimeMillis()) { // query all timers ready at this moment, ordered by flow HibernateUtil.beginTransaction(); HibernateUtil.readOnlySession(); Query qry = HibernateUtil.getSession().getNamedQuery("Timer.getReadyTimers"); qry.setTimestamp("fromTime", new Date()); List<ActivityTimer> timers = qry.list(); HibernateUtil.commitTransaction(); HibernateUtil.closeSession(); // for each timer for (ActivityTimer att : timers) { try { Activity act = att.getActivity(); String timerId = att.getTimerId(); HibernateUtil.beginTransaction(); // if activity not dead if (act != null && act.getSubmitId() != null && act.getStates().containsKey(timerId)) { HibernateUtil.getSession().refresh(act); AuthenticatedUser aUser = UserSpaceAdmin.getAuthUser(act.getSubmitId()); UserSpace uspace = aUser != null ? UserSpaceAdmin.getUserSpace(act.getUserSpaceId()) : null; if (aUser == null || uspace == null) { HibernateUtil.getSession().delete(att); continue; } aUser.setActiveUserSpace(uspace); // switch user SecurityAssociation.setUser(aUser); // get runner try { Runner<Activity, String> run = getRunner(act); // fire! try { run.handleEvent(new FlowEvent<Activity, String>(act, timerId)); } catch (RunException re) { // TODO - alert the activity owner log.warn(re); FlowModel mod = run.getModel(); Step stp = mod.getStep(timerId); boolean killTimer = false; if (stp == null) { killTimer = true; } else { Collection<Path> paths = stp.getPaths(); if (paths.isEmpty()) killTimer = true; else for (Path pth : paths) { if (pth.getToStep() == null) { killTimer = true; break; } } } if (killTimer) HibernateUtil.getSession().delete(att); } } catch (NotFoundException nfe) { log.warn(nfe); HibernateUtil.getSession().delete(att); } } else { HibernateUtil.getSession().delete(att); } // update checkTime HibernateUtil.commitTransaction(); } catch (Exception ex) { log.error(ex); HibernateUtil.rollbackTransaction(); } // switch user back to super SecurityAssociation.setUser(SysAdmin.getUser()); } // end for loop HibernateUtil.closeSession(); clearRunner(); // query for next timer HibernateUtil.beginTransaction(); HibernateUtil.readOnlySession(); qry = HibernateUtil.getSession().getNamedQuery("Timer.getNextTimer"); qry.setMaxResults(1); Iterator<ActivityTimer> atItr = qry.iterate(); ActivityTimer nxtActTimer = atItr.hasNext() ? atItr.next() : null; nextTimer = nxtActTimer != null ? nxtActTimer.getAtTime() : null; HibernateUtil.commitTransaction(); HibernateUtil.closeSession(); Thread.yield(); } // query a batch conditionals with older checkTimes, ordered by flow HibernateUtil.beginTransaction(); HibernateUtil.readOnlySession(); Query qry = HibernateUtil.getSession().getNamedQuery("Timer.getCondTimers"); qry.setMaxResults(53); List<ActivityTimer> timers = qry.list(); HibernateUtil.commitTransaction(); HibernateUtil.closeSession(); // for each conditional timer for (ActivityTimer att : timers) { try { Activity act = att.getActivity(); String timerId = att.getTimerId(); HibernateUtil.beginTransaction(); // if activity not dead if (act != null && act.getSubmitId() != null && act.getStates().containsKey(timerId)) { HibernateUtil.getSession().refresh(act); AuthenticatedUser aUser = UserSpaceAdmin.getAuthUser(act.getSubmitId()); UserSpace uspace = aUser != null ? UserSpaceAdmin.getUserSpace(act.getUserSpaceId()) : null; if (aUser == null || uspace == null) { HibernateUtil.getSession().delete(att); continue; } aUser.setActiveUserSpace(uspace); // switch user SecurityAssociation.setUser(aUser); // get runner Runner<Activity, String> run; try { run = getRunner(act); } catch (NotFoundException nfe) { log.warn(nfe); HibernateUtil.getSession().delete(att); HibernateUtil.commitTransaction(); continue; } // get the condition from the model Step step = run.getModel().getStep(timerId); if (step != null && step instanceof Timer) { Timer timerDef = (Timer) step; Until ud = timerDef.selectOneChild(Until.class); Condition cond = ud != null ? ud.selectOneChild(Condition.class) : null; if (cond != null) { // test condition FlowEvent<Activity, String> evt = new FlowEvent<Activity, String>(act, timerId); Condition conds[] = new Condition[] { cond, null }; String ret = run.getEvals().evalExclusive(act.getFlow().getId(), conds, evt); if (ret != null) { run.handleEvent(evt); } else { att.setCheckTime(new Date()); HibernateUtil.getSession().update(att); } } else { log.warn("Condition missing: " + act.getFlow().getNode().getUri() + "#" + timerId); HibernateUtil.getSession().delete(att); } } else { log.warn("Timer missing: " + act.getFlow().getNode().getUri() + "#" + timerId); HibernateUtil.getSession().delete(att); } } else { HibernateUtil.getSession().delete(att); } act.clearCache(); // update checkTime HibernateUtil.commitTransaction(); } catch (Exception ex) { log.error(ex); HibernateUtil.rollbackTransaction(); } // switch user back to super SecurityAssociation.setUser(SysAdmin.getUser()); Thread.yield(); } // end for loop HibernateUtil.closeSession(); clearRunner(); synchronized (ActivityStateStore.timerSync) { ActivityStateStore.timerSync.notifyAll(); } // schedule some sleep try { if (nextTimer != null && (nextTimer.getTime() - System.currentTimeMillis()) < sleepTime) { long slp = nextTimer.getTime() - System.currentTimeMillis(); Thread.sleep(slp > 50 ? slp : 50); } else { Thread.sleep(sleepTime); } } catch (InterruptedException e) { log.info(e); keepRunning = false; } } catch (Exception ex) { log.error(ex); // probably DB offline, keep trying Thread.yield(); } } }
From source file:kz.app.dao.GoodsSupDao.java
public List<GoodsSupEntity> getListSups(Date begin, Date end) { Session session = HibernateUtil.getSession(); try {/*from w w w . ja v a2s .c om*/ session.beginTransaction(); Query query = HibernateUtil.getSessionfactory().getCurrentSession() .createQuery("from GoodsSupEntity where date between :begin and :end"); query.setTimestamp("begin", begin); query.setTimestamp("end", end); List<GoodsSupEntity> list = query.list(); session.getTransaction().commit(); if (list.isEmpty()) return null; return list; } catch (RuntimeException e) { session.getTransaction().rollback(); throw e; } finally { if (session.isOpen()) session.close(); } }
From source file:mitm.common.security.certstore.dao.X509CertStoreDAOHibernate.java
License:Open Source License
private Query createByEmailQuery(String baseQuery, String email, Match match, Expired expired, MissingKeyAlias missingKeyAlias, Date date) { if (email != null) { baseQuery = baseQuery + " join c.email e where e"; baseQuery = baseQuery + (match == Match.EXACT ? " = :email" : " like :email"); } else {//from ww w .j a v a2s.c om /* if email is null we want to get all the entries without an email address */ baseQuery = baseQuery + " left join c.email e where e is null"; } if (expired == Expired.NOT_ALLOWED) { baseQuery = baseQuery + " and :time between notBefore and notAfter"; } if (missingKeyAlias == MissingKeyAlias.NOT_ALLOWED) { baseQuery = baseQuery + " and keyAlias is not null"; } baseQuery = baseQuery + " and storeName = :storeName"; Query query = createQuery(baseQuery); if (email != null) { email = email.toLowerCase().trim(); query.setString("email", email); } if (expired == Expired.NOT_ALLOWED) { query.setTimestamp("time", date); } query.setString(getColumnName(Field.STORE_NAME), storeName); return query; }