Esempio n. 1
0
  /**
   * Reads in all VehicleEvents from the database that were between the beginTime and endTime.
   *
   * @param agencyId Which project getting data for
   * @param beginTime Specifies time range for query
   * @param endTime Specifies time range for query
   * @param sqlClause Optional. Can specify an SQL clause to winnow down the data, such as "AND
   *     routeId='71'".
   * @return
   */
  public static List<VehicleEvent> getVehicleEvents(
      String agencyId, Date beginTime, Date endTime, String sqlClause) {
    IntervalTimer timer = new IntervalTimer();

    // Get the database session. This is supposed to be pretty light weight
    Session session = HibernateUtils.getSession(agencyId);

    // Create the query. Table name is case sensitive and needs to be the
    // class name instead of the name of the db table.
    String hql =
        "FROM VehicleEvent " + "    WHERE time >= :beginDate " + "      AND time < :endDate";
    if (sqlClause != null) hql += " " + sqlClause;
    Query query = session.createQuery(hql);

    // Set the parameters
    query.setTimestamp("beginDate", beginTime);
    query.setTimestamp("endDate", endTime);

    try {
      @SuppressWarnings("unchecked")
      List<VehicleEvent> vehicleEvents = query.list();
      logger.debug("Getting VehicleEvents from database took {} msec", timer.elapsedMsec());
      return vehicleEvents;
    } catch (HibernateException e) {
      logger.error(e.getMessage(), e);
      return null;
    } finally {
      // Clean things up. Not sure if this absolutely needed nor if
      // it might actually be detrimental and slow things down.
      session.close();
    }
  }
 @Override
 public List<DasControlDevice> listCdInfo(List<String> sns) {
   Session session = getSessionDas();
   Query query =
       session.createSQLQuery(
           SqlFactory.getInstance().getListSQL(TypeDefinition.TABLE_NAME_CD, sns.size()));
   int index = 0;
   for (String sn : sns) {
     query.setString(index++, sn);
   }
   // 只查最近一天的
   query.setTimestamp(index, new Date(System.currentTimeMillis() - 86400000));
   List<Object[]> rows = query.list();
   List<DasControlDevice> list = new LinkedList<DasControlDevice>();
   for (Object[] row : rows) {
     index = 0;
     DasControlDevice cd = new DasControlDevice();
     cd.setId(MyStringUtil.object2String(row[index++]));
     cd.setStandardNumber(MyStringUtil.object2String(row[index++]));
     cd.setRecTime((Timestamp) row[index++]);
     cd.setType(NumberUtil.getInteger(row[index++]));
     cd.setWorkState(MyStringUtil.object2String(row[index++]));
     cd.setStatus(NumberUtil.getShort(row[index++]));
     cd.setCommStatus(NumberUtil.getShort(row[index++]));
     cd.setReserve(MyStringUtil.object2String(row[index++]));
     cd.setOrgan(MyStringUtil.object2String(row[index++]));
     list.add(cd);
   }
   return list;
 }
Esempio n. 3
0
  public static String returnItem(String recordId) {
    System.out.println("what happened");

    String record = DBQuerrier.getRecord(recordId);
    if (record.equals("[]")) return "[0]";

    String[] paras = record.split(",");
    // if(!("0".equals(paras[paras.length-2])))
    // return "[0]";

    int borrowCount = 0;
    try {
      borrowCount =
          Integer.parseInt(
              (paras[paras.length - 1].substring(0, paras[paras.length - 1].length() - 1)));
    } catch (Exception e) {
      // TODO: handle exception
    }
    System.out.println("woca" + borrowCount);
    Session session = sessionStart();
    Transaction tx = session.beginTransaction();
    String hql = "update Borrowrecord br set br.returnDate = ? where br.recordId = ?";
    Query query = ((SharedSessionContract) session).createQuery(hql);

    int recordIdInt = 0;

    try {
      recordIdInt = Integer.parseInt(recordId);
    } catch (Exception e) {
      // TODO: handle exception
      return "[0]";
    }
    Date currenTimeDate = new Date();
    query.setTimestamp(0, currenTimeDate);
    query.setInteger(1, recordIdInt);

    int resInt = query.executeUpdate();
    tx.commit();
    session.close();

    // return done , update count
    if (!("".equals(paras[3]))) {
      session = sessionStart();
      tx = session.beginTransaction();
      hql = "update Iteminfo ii set ii.leftcount = ii.leftcount + ? where ii.id = ?";
      query = ((SharedSessionContract) session).createQuery(hql);
      query.setInteger(0, borrowCount);
      int itemIdInt = 0;
      itemIdInt = Integer.parseInt(paras[3]);
      query.setInteger(1, itemIdInt);
      query.executeUpdate();
      tx.commit();
      session.close();
    }

    return "[" + resInt + "]";
  }
Esempio n. 4
0
 public List<Login> findLockedUsers(Date startTime) {
   Session session = sessionFactory.getCurrentSession();
   Query qry =
       session.createQuery(
           "from org.openiam.idm.srvc.auth.dto.Login l "
               + " where l.isLocked = 1 and  "
               + "  l.lastAuthAttempt >= :startTime ");
   qry.setTimestamp("startTime", startTime);
   return (List<Login>) qry.list();
 }
Esempio n. 5
0
 /** {@inheritDoc} */
 public TypedQuery<X> setParameter(String name, Date value, TemporalType temporalType) {
   try {
     if (temporalType == DATE) {
       query.setDate(name, value);
     } else if (temporalType == TIME) {
       query.setTime(name, value);
     } else if (temporalType == TIMESTAMP) {
       query.setTimestamp(name, value);
     }
     registerParameterBinding(getParameter(name), value);
     return this;
   } catch (QueryParameterException e) {
     throw new IllegalArgumentException(e);
   } catch (HibernateException he) {
     throw getEntityManager().convert(he);
   }
 }
Esempio n. 6
0
 protected void setParameter(Query query, String paramName, Object paramValue) {
   if (paramValue instanceof String) {
     query.setString(paramName, (String) paramValue);
   } else if (paramValue instanceof Integer) {
     query.setInteger(paramName, (Integer) paramValue);
   } else if (paramValue instanceof Long) {
     query.setLong(paramName, (Long) paramValue);
   } else if (paramValue instanceof Double) {
     query.setDouble(paramName, (Double) paramValue);
   } else if (paramValue instanceof Boolean) {
     query.setBoolean(paramName, (Boolean) paramValue);
   } else if (paramValue instanceof Date) {
     // TODO 难道这是bug 使用setParameter不行??
     query.setTimestamp(paramName, (Date) paramValue);
   } else if (paramValue instanceof Collection) {
     query.setParameterList(paramName, (Collection<?>) paramValue);
   } else {
     query.setParameter(paramName, paramValue);
   }
 }
Esempio n. 7
0
  public void applySQLParameter(Query q) {
    Iterator<String> it = parameterMap.keySet().iterator();

    while (it.hasNext()) {
      String key = it.next();
      HQLObject obj = parameterMap.get(key);

      String s = "";

      if (obj.obj instanceof String) {
        if (obj.wholeWords) {
          s = obj.obj.toString();
        } else {
          s = "%" + obj.obj.toString() + "%";
        }
        q.setString("s_" + obj.fieldName, s);
      } else if (obj.obj instanceof java.util.Date) {
        // SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // s = sdf.format(obj.obj);

        // q.setDate("s_" + obj.fieldName, (java.util.Date)obj.obj);
        q.setTimestamp("s_" + obj.fieldName, (java.util.Date) obj.obj);
        // logger.debug("SDF: " + sdf.format(obj.obj));
      } else if (obj.obj instanceof Boolean) {
        // s = Boolean.parseBoolean(obj.obj.toString()) ? "1" : "0";
        q.setBoolean("s_" + obj.fieldName, (Boolean) obj.obj);
        // logger.debug("Bool: " + s);
      } else if (obj.obj instanceof Integer) {
        // s = ((Integer)obj.obj).toString();
        q.setInteger("s_" + obj.fieldName, (Integer) obj.obj);
      } else if (obj.obj instanceof Long) {
        // s = ((Integer)obj.obj).toString();
        q.setLong("s_" + obj.fieldName, (Long) obj.obj);
      } else {
        s = obj.obj.toString();
        q.setString("s_" + obj.fieldName, s);

        logger.warn("Typ nicht gefunden: " + obj.obj.getClass().getCanonicalName());
      }
    }
  }
Esempio n. 8
0
  @Override
  public Iterator<Item> findAll(
      Context context, boolean archived, boolean withdrawn, boolean discoverable, Date lastModified)
      throws SQLException {
    StringBuilder queryStr = new StringBuilder();
    queryStr.append("SELECT i FROM Item i");
    queryStr.append(" WHERE (inArchive = :in_archive OR withdrawn = :withdrawn)");
    queryStr.append(" AND discoverable = :discoverable");

    if (lastModified != null) {
      queryStr.append(" AND last_modified > :last_modified");
    }

    Query query = createQuery(context, queryStr.toString());
    query.setParameter("in_archive", archived);
    query.setParameter("withdrawn", withdrawn);
    query.setParameter("discoverable", discoverable);
    if (lastModified != null) {
      query.setTimestamp("last_modified", lastModified);
    }
    return iterate(query);
  }
 @SuppressWarnings("unchecked")
 public Double getTicketPrice(List<TripBean> trips, Date date) {
   List<Double> result = null;
   Query query = null;
   String queryString = null;
   Session session = null;
   // get the current session
   session = sessionFactory.getCurrentSession();
   try {
     // perform database access (query, insert, update, etc) here
     queryString =
         "SELECT SUM(tar.fare) FROM TariffViewBean AS tar INNER JOIN tar.segment.routeDetails as rds INNER JOIN rds.trips AS trp INNER JOIN trp.busStatus.bus AS bus WHERE trp IN (:trips) AND tar.busType = bus.busType AND tar.validFrom <= :date AND (tar.validTo > :date OR tar.validTo = null)";
     query = session.createQuery(queryString);
     query.setParameterList("trips", trips);
     query.setTimestamp("date", date);
     result = query.list();
   } catch (HibernateException e) {
     exceptionHandling(e, session);
   }
   // return result, if needed
   return result == null || result.size() <= 0 ? null : result.get(0);
 }
Esempio n. 10
0
 /** {@inheritDoc} */
 public TypedQuery<X> setParameter(int position, Date value, TemporalType temporalType) {
   try {
     if (isJpaPositionalParameter(position)) {
       String name = Integer.toString(position);
       this.setParameter(name, value, temporalType);
     } else {
       if (temporalType == DATE) {
         query.setDate(position - 1, value);
       } else if (temporalType == TIME) {
         query.setTime(position - 1, value);
       } else if (temporalType == TIMESTAMP) {
         query.setTimestamp(position - 1, value);
       }
       registerParameterBinding(getParameter(position), value);
     }
     return this;
   } catch (QueryParameterException e) {
     throw new IllegalArgumentException(e);
   } catch (HibernateException he) {
     throw getEntityManager().convert(he);
   }
 }
Esempio n. 11
0
 /**
  * 分页浏览某个论坛的热门帖子 帖子按照回帖数
  *
  * @param forum_id
  * @param fromIdx
  * @param count
  * @return
  */
 public static List listHotTopics(
     SiteBean site, ForumBean forum, int fromIdx, int count, int days) {
   StringBuffer hql =
       new StringBuffer(
           "FROM TopicOutlineBean AS t WHERE t.site.id=? AND t.status=? AND t.createTime >= ? AND t.replyCount > 0");
   if (forum != null) hql.append(" AND t.forum.id=?");
   hql.append(" ORDER BY ROUND(t.type / 16, 0) DESC, t.replyCount DESC, t.id DESC");
   Session ssn = getSession();
   try {
     Query q = ssn.createQuery(hql.toString());
     q.setInteger(0, site.getId());
     q.setInteger(1, TopicOutlineBean.STATUS_NORMAL);
     Calendar cur_time = Calendar.getInstance();
     cur_time.add(Calendar.DATE, -days);
     q.setTimestamp(2, new Timestamp(cur_time.getTime().getTime()));
     if (forum != null) q.setInteger(3, forum.getId());
     if (fromIdx > 0) q.setFirstResult(fromIdx);
     q.setMaxResults(count);
     return q.list();
   } finally {
     hql = null;
   }
 }
Esempio n. 12
0
  public List getMessageList(
      Integer fromId,
      Integer toId,
      Integer state,
      Integer type,
      Date startTime,
      Date endTime,
      int start,
      int end) {
    try {
      String hql = "from Message m where 1=1 ";
      if (fromId != null) {
        hql += " and m.fromid=?";
      }
      if (toId != null) {
        hql += " and m.toid=?";
      }
      if (state != null) {
        hql += " and m.state=?";
      }
      if (type != null) {
        hql += " and m.type=?";
      }
      if (startTime != null) {
        hql += " and m.createTime>=?";
      }
      if (endTime != null) {
        hql += " and m.createTime<=?";
      }

      Query query = this.getQuery(hql);
      int index = 0;
      if (fromId != null) {
        query.setParameter(index, fromId);
        index++;
      }
      if (toId != null) {
        query.setParameter(index, toId);
        index++;
      }
      if (state != null) {
        query.setParameter(index, state);
        index++;
      }
      if (type != null) {
        query.setParameter(index, type);
        index++;
      }
      if (startTime != null) {
        query.setTimestamp(index, startTime);
        index++;
      }
      if (endTime != null) {
        query.setTimestamp(index, endTime);
        index++;
      }

      query.setFirstResult(start);
      query.setMaxResults(end - start);
      return query.list();
    } catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }
Esempio n. 13
0
  /**
   * Fetch all the matching patients from all the community and all assigning authorities on a known
   * id.
   *
   * @param Patient
   * @return Patient
   */
  public List<Patient> findPatients(Patient patient) {
    log.debug("PatientDAO.findAllPatients() - Begin");

    Session session = null;
    List<Patient> patientsList = new ArrayList<Patient>();

    try {
      SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
      session = sessionFactory.openSession();

      log.info("Reading Records...");

      // NHIN required query parameters
      String gender = patient.getGender();
      Timestamp dateOfBirth = patient.getDateOfBirth();
      String firstName = patient.getPersonnames().get(0).getFirstName();
      String lastName = patient.getPersonnames().get(0).getLastName();
      // NHIN optional query parameters
      String ssn = patient.getSsn();
      String prefix = patient.getPersonnames().get(0).getPrefix();
      String middleName = patient.getPersonnames().get(0).getMiddleName();
      String suffix = patient.getPersonnames().get(0).getSuffix();

      Address address = new Address();
      if (patient.getAddresses() != null && patient.getAddresses().size() > 0) {
        address = patient.getAddresses().get(0);
      }
      Phonenumber phonenumber = new Phonenumber();
      if (patient.getPhonenumbers() != null && patient.getPhonenumbers().size() > 0) {
        phonenumber = patient.getPhonenumbers().get(0);
      }

      // Build the select with query criteria
      StringBuffer sqlSelect =
          new StringBuffer(
              "SELECT DISTINCT p.patientId, p.dateOfBirth, p.gender, p.ssn, i.id, i.organizationid");
      sqlSelect.append(" FROM patientdb.patient p");
      sqlSelect.append(" INNER JOIN patientdb.identifier i ON p.patientId = i.patientId");
      sqlSelect.append(" INNER JOIN patientdb.personname n ON p.patientId = n.patientId");
      if (address.getAddressId() != null) {
        sqlSelect.append(" INNER JOIN patientdb.address a ON p.patientId = a.patientId");
      }
      if (phonenumber.getPhonenumberId() != null) {
        sqlSelect.append(" INNER JOIN patientdb.phonenumber h ON p.patientId = h.patientId");
      }

      StringBuffer criteriaString = new StringBuffer("");
      if (NullChecker.isNotNullish(gender)) {
        if (criteriaString.length() > 0) {
          criteriaString.append(" AND");
        } else {
          criteriaString.append(" WHERE");
        }
        criteriaString.append(" p.gender = ?");
      }
      if (dateOfBirth != null) {
        if (criteriaString.length() > 0) {
          criteriaString.append(" AND");
        } else {
          criteriaString.append(" WHERE");
        }
        criteriaString.append(" p.dateOfBirth = ?");
      }
      if (NullChecker.isNotNullish(firstName)) {
        if (criteriaString.length() > 0) {
          criteriaString.append(" AND");
        } else {
          criteriaString.append(" WHERE");
        }
        criteriaString.append(" n.firstname = ?");
      }
      if (NullChecker.isNotNullish(lastName)) {
        if (criteriaString.length() > 0) {
          criteriaString.append(" AND");
        } else {
          criteriaString.append(" WHERE");
        }
        criteriaString.append(" n.lastname = ?");
      }
      if (NullChecker.isNotNullish(ssn)) {
        if (criteriaString.length() > 0) {
          criteriaString.append(" AND");
        } else {
          criteriaString.append(" WHERE");
        }
        criteriaString.append(" p.ssn = ?");
      }
      if (NullChecker.isNotNullish(prefix)) {
        if (criteriaString.length() > 0) {
          criteriaString.append(" AND");
        } else {
          criteriaString.append(" WHERE");
        }
        criteriaString.append(" n.prefix = ?");
      }
      if (NullChecker.isNotNullish(middleName)) {
        if (criteriaString.length() > 0) {
          criteriaString.append(" AND");
        } else {
          criteriaString.append(" WHERE");
        }
        criteriaString.append(" n.middleName = ?");
      }
      if (NullChecker.isNotNullish(suffix)) {
        if (criteriaString.length() > 0) {
          criteriaString.append(" AND");
        } else {
          criteriaString.append(" WHERE");
        }
        criteriaString.append(" n.suffix = ?");
      }
      if (address.getAddressId() != null && NullChecker.isNotNullish(address.getStreet1())) {
        if (criteriaString.length() > 0) {
          criteriaString.append(" AND");
        } else {
          criteriaString.append(" WHERE");
        }
        criteriaString.append(" a.street1 = ?");
      }
      if (address.getAddressId() != null && NullChecker.isNotNullish(address.getStreet2())) {
        if (criteriaString.length() > 0) {
          criteriaString.append(" AND");
        } else {
          criteriaString.append(" WHERE");
        }
        criteriaString.append(" a.street2 = ?");
      }
      if (address.getAddressId() != null && NullChecker.isNotNullish(address.getCity())) {
        if (criteriaString.length() > 0) {
          criteriaString.append(" AND");
        } else {
          criteriaString.append(" WHERE");
        }
        criteriaString.append(" a.city = ?");
      }
      if (address.getAddressId() != null && NullChecker.isNotNullish(address.getState())) {
        if (criteriaString.length() > 0) {
          criteriaString.append(" AND");
        } else {
          criteriaString.append(" WHERE");
        }
        criteriaString.append(" a.state = ?");
      }
      if (address.getAddressId() != null && NullChecker.isNotNullish(address.getPostal())) {
        if (criteriaString.length() > 0) {
          criteriaString.append(" AND");
        } else {
          criteriaString.append(" WHERE");
        }
        criteriaString.append(" a.postal = ?");
      }
      if (phonenumber.getPhonenumberId() != null
          && NullChecker.isNotNullish(phonenumber.getValue())) {
        if (criteriaString.length() > 0) {
          criteriaString.append(" AND");
        } else {
          criteriaString.append(" WHERE");
        }
        criteriaString.append(" h.value = ?");
      }
      sqlSelect.append(criteriaString);

      sqlSelect.append(" ORDER BY i.id, i.organizationid");

      Query sqlQuery =
          session
              .createSQLQuery(sqlSelect.toString())
              .addScalar("patientId", Hibernate.LONG)
              .addScalar("dateOfBirth", Hibernate.TIMESTAMP)
              .addScalar("gender", Hibernate.STRING)
              .addScalar("ssn", Hibernate.STRING)
              .addScalar("id", Hibernate.STRING)
              .addScalar("organizationid", Hibernate.STRING);

      int iParam = 0;
      if (NullChecker.isNotNullish(gender)) {
        sqlQuery.setString(iParam, gender);
        iParam++;
      }
      if (dateOfBirth != null) {
        sqlQuery.setTimestamp(iParam, dateOfBirth);
        iParam++;
      }
      if (NullChecker.isNotNullish(firstName)) {
        sqlQuery.setString(iParam, firstName);
        iParam++;
      }
      if (NullChecker.isNotNullish(lastName)) {
        sqlQuery.setString(iParam, lastName);
        iParam++;
      }
      if (NullChecker.isNotNullish(ssn)) {
        sqlQuery.setString(iParam, ssn);
        iParam++;
      }
      if (NullChecker.isNotNullish(prefix)) {
        sqlQuery.setString(iParam, prefix);
        iParam++;
      }
      if (NullChecker.isNotNullish(middleName)) {
        sqlQuery.setString(iParam, middleName);
        iParam++;
      }
      if (NullChecker.isNotNullish(suffix)) {
        sqlQuery.setString(iParam, suffix);
        iParam++;
      }
      if (address.getAddressId() != null && NullChecker.isNotNullish(address.getStreet1())) {
        sqlQuery.setString(iParam, address.getStreet1());
        iParam++;
      }
      if (address.getAddressId() != null && NullChecker.isNotNullish(address.getStreet2())) {
        sqlQuery.setString(iParam, address.getStreet2());
        iParam++;
      }
      if (address.getAddressId() != null && NullChecker.isNotNullish(address.getCity())) {
        sqlQuery.setString(iParam, address.getCity());
        iParam++;
      }
      if (address.getAddressId() != null && NullChecker.isNotNullish(address.getState())) {
        sqlQuery.setString(iParam, address.getState());
        iParam++;
      }
      if (address.getAddressId() != null && NullChecker.isNotNullish(address.getPostal())) {
        sqlQuery.setString(iParam, address.getPostal());
        iParam++;
      }
      if (phonenumber.getPhonenumberId() != null
          && NullChecker.isNotNullish(phonenumber.getValue())) {
        sqlQuery.setString(iParam, phonenumber.getValue());
        iParam++;
      }

      log.debug("Final SQL Query is " + sqlQuery.getQueryString());

      List<Object[]> result = sqlQuery.list();

      if (result != null && result.size() > 0) {
        Long[] patientIdArray = new Long[result.size()];
        Timestamp[] dateOfBirthArray = new Timestamp[result.size()];
        String[] genderArray = new String[result.size()];
        String[] ssnArray = new String[result.size()];
        String[] idArray = new String[result.size()];
        String[] organizationIdArray = new String[result.size()];

        int counter = 0;
        for (Object[] row : result) {
          patientIdArray[counter] = (Long) row[0];
          dateOfBirthArray[counter] = (Timestamp) row[1];
          genderArray[counter] = row[2].toString();
          ssnArray[counter] = row[3].toString();
          idArray[counter] = row[4].toString();
          organizationIdArray[counter] = row[5].toString();
          counter++;
        }

        for (int i = 0; i < patientIdArray.length; i++) {
          Patient patientData = new Patient();
          patientData.setPatientId(patientIdArray[i]);
          patientData.setDateOfBirth(dateOfBirthArray[i]);
          patientData.setGender(genderArray[i]);
          patientData.setSsn(ssnArray[i]);

          Identifier identifierData = new Identifier();
          identifierData.getPatient().setPatientId(patientIdArray[i]);
          identifierData.setId(idArray[i]);
          identifierData.setOrganizationId(organizationIdArray[i]);

          patientData.getIdentifiers().add(identifierData);

          // Populate demographic data
          patientData.setAddresses(
              AddressDAO.getAddressDAOInstance().findPatientAddresses(patientIdArray[i]));
          patientData.setPersonnames(
              PersonnameDAO.getPersonnameDAOInstance().findPatientPersonnames(patientIdArray[i]));
          patientData.setPhonenumbers(
              PhonenumberDAO.getPhonenumberDAOInstance()
                  .findPatientPhonenumbers(patientIdArray[i]));

          patientsList.add(patientData);
        }
      }

    } catch (Exception e) {
      log.error("Exception during read occured due to : " + e.getMessage(), e);
    } finally {
      // Flush and close session
      if (session != null) {
        session.flush();
        session.close();
      }
    }
    log.debug("PatientDAO.findPatients() - End");
    return patientsList;
  }
Esempio n. 14
0
  /* (non-Javadoc)
   * @see it.eng.spagobi.monitoring.dao.IAuditDAO#getLastExecution(java.lang.Integer)
   */
  public SbiAudit getLastExecution(Integer objId) throws EMFUserError {
    logger.debug("IN");
    Session aSession = null;
    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;
  }
Esempio n. 15
0
 @Override
 public Iterator<Item> findByLastModifiedSince(Context context, Date since) throws SQLException {
   Query query = createQuery(context, "SELECT i FROM item i WHERE last_modified > :last_modified");
   query.setTimestamp("last_modified", since);
   return iterate(query);
 }
Esempio n. 16
0
  /* (non-Javadoc)
   * @see org.openiam.idm.srvc.auth.login.LoginDAO#bulkUnlock(org.openiam.idm.srvc.user.dto.UserStatusEnum)
   */
  public int bulkUnlock(String domainId, UserStatusEnum status, int autoUnlockTime) {

    log.debug("bulkUnlock operation in LoginDAO called.");
    Session session = sessionFactory.getCurrentSession();

    String userQry =
        " UPDATE org.openiam.idm.srvc.user.dto.User u  "
            + " SET u.secondaryStatus = null "
            + " where u.secondaryStatus = 'LOCKED' and "
            + "       u.userId in ("
            + " 	select l.userId from org.openiam.idm.srvc.auth.dto.Login as l  "
            + "       where l.id.domainId = :domain and  "
            + "             l.isLocked = :status and "
            + "             l.lastAuthAttempt <= :policyTime"
            + "   )";

    String loginQry =
        " UPDATE org.openiam.idm.srvc.auth.dto.Login l  "
            + " SET l.isLocked = 0, "
            + "     l.authFailCount = 0 "
            + "       where l.id.domainId = :domain and  "
            + "             l.isLocked = :status and "
            + "             l.lastAuthAttempt <= :policyTime";

    Query qry = session.createQuery(userQry);

    Date policyTime = new Date(System.currentTimeMillis());

    log.debug("Auto unlock time:" + autoUnlockTime);

    Calendar c = Calendar.getInstance();
    c.setTime(policyTime);
    c.add(Calendar.MINUTE, (-1 * autoUnlockTime));
    policyTime.setTime(c.getTimeInMillis());

    log.debug("Policy time=" + policyTime.toString());

    qry.setString("domain", domainId);

    log.debug("DomainId=" + domainId);

    int statusParam = 0;
    if (status.equals(UserStatusEnum.LOCKED)) {
      statusParam = 1;
      // qry.setInteger("status", 1);
      log.debug("status=1");
    } else {
      statusParam = 2;
      // qry.setInteger("status", 2);
      log.debug("status=2");
    }

    qry.setInteger("status", statusParam);
    qry.setTimestamp("policyTime", policyTime);
    int rowCount = qry.executeUpdate();

    log.debug("Bulk unlock updated:" + rowCount);

    if (rowCount > 0) {

      Query lQry = session.createQuery(loginQry);
      lQry.setString("domain", domainId);
      lQry.setInteger("status", statusParam);
      lQry.setTimestamp("policyTime", policyTime);
      lQry.executeUpdate();
    }

    return rowCount;
  }