@Override
  public Long countParceirosInscritos(
      Integer idCursoSelecionado, Integer idGradeOficina, List<Integer> idsParceiros) {

    List<Integer> idsStatus = new ArrayList<Integer>();
    idsStatus.add(Status.CANCELADO);
    idsStatus.add(Status.AGUARDANDO_VAGA_PRIORIDADE);
    idsStatus.add(Status.AGUARDANDO_VAGA);

    Criteria criteria = getSession().createCriteria(InscricaoGrade.class);
    criteria.createAlias("inscricaoCurso", "ic");
    criteria.createAlias("ic.curso", "c");
    criteria.add(Restrictions.eq("c.id", idCursoSelecionado));
    criteria.createAlias("ic.ultimoStatus", "us");
    criteria.createAlias("us.status", "s");
    criteria.add(Restrictions.not(Restrictions.in("s.id", idsStatus)));
    criteria.createAlias("gradeOficina", "go");
    criteria.add(Restrictions.eq("go.id", idGradeOficina));
    if (idsParceiros != null && !idsParceiros.isEmpty()) {
      criteria.createAlias("ic.candidato", "cand");
      criteria.add(Restrictions.in("cand.id", idsParceiros));
    }
    criteria.setProjection(Projections.rowCount());
    Long result = (Long) criteria.list().get(0);
    return result;
  }
Exemplo n.º 2
0
  @Secured({"ROLE_DEVELOPER", "ROLE_TESTER"})
  @RequestMapping("goAddBug.htm")
  public ModelAndView goAddBug(HttpServletRequest request) {

    Company company = (Company) request.getSession().getAttribute("company");
    DetachedCriteria dCriteria = DetachedCriteria.forClass(Project.class);
    dCriteria.add(Restrictions.eq("company", company));
    List<Project> projectList = aService.queryAllOfCondition(Project.class, dCriteria);

    DetachedCriteria dCriteria1 = DetachedCriteria.forClass(Department.class);
    dCriteria1.add(Restrictions.eq("company", company));
    List<Department> deptList = aService.queryAllOfCondition(Department.class, dCriteria1);

    DetachedCriteria dCriteria2 = DetachedCriteria.forClass(Developer.class);
    dCriteria2.createCriteria("user").add(Restrictions.in("department", deptList));
    List<Developer> userList = aService.queryAllOfCondition(Developer.class, dCriteria2);

    DetachedCriteria dCriteria3 = DetachedCriteria.forClass(User.class);
    dCriteria3.add(Restrictions.in("department", deptList));
    List<User> userList1 = aService.queryAllOfCondition(User.class, dCriteria3);

    ModelMap map = new ModelMap();
    map.put("projectList", projectList);
    map.put("userList", userList);
    map.put("userList1", userList1);

    return new ModelAndView("/bug/addBug", map);
  }
Exemplo n.º 3
0
  @SuppressWarnings("rawtypes")
  public List<Criterion> restrict(Object[]... values) {

    List<Criterion> criterions = new ArrayList<Criterion>();
    switch (valueOf(type)) {
      case IN:
        for (Object[] value : values)
          criterions.add(Restrictions.in((String) value[0], (Collection) value[1]));

        break;
      case NOTIN:
        for (Object[] value : values)
          criterions.add(
              Restrictions.not(Restrictions.in((String) value[0], (Collection) value[1])));
        break;
      case EQ:
        for (Object[] value : values) criterions.add(Restrictions.eq((String) value[0], value[1]));
        break;
      case NOTEQ:
        for (Object[] value : values) criterions.add(Restrictions.ne((String) value[0], value[1]));
        break;
      case GE:
        for (Object[] value : values) criterions.add(Restrictions.ge((String) value[0], value[1]));
        break;
      case LE:
        for (Object[] value : values) criterions.add(Restrictions.le((String) value[0], value[1]));
        break;
      case BETWEEN:
        for (Object[] value : values)
          criterions.add(Restrictions.between((String) value[0], value[1], value[2]));
        break;
      case GT:
        for (Object[] value : values) criterions.add(Restrictions.gt((String) value[0], value[1]));
        break;
      case LT:
        for (Object[] value : values) criterions.add(Restrictions.lt((String) value[0], value[1]));
        break;
      case AND:
        for (Object[] value : values)
          criterions.add(Restrictions.and((Criterion) value[0], (Criterion) value[1]));
        break;
      case OR:
        for (Object[] value : values)
          criterions.add(Restrictions.or((Criterion) value[0], (Criterion) value[1]));
        break;
      case NULL:
        for (Object[] value : values) criterions.add(Restrictions.isNull((String) value[0]));
        break;
      case NOTNULL:
        for (Object[] value : values) criterions.add(Restrictions.isNotNull((String) value[0]));
        break;
      case LIKE:
        for (Object[] value : values)
          criterions.add(Restrictions.like((String) value[0], value[1]));
        break;
    }
    return criterions;
  }
Exemplo n.º 4
0
  @Override
  public Condition buildCondition(
      String conditionField, ConditionType conditionType, Iterator argsIterator) {
    Condition condition = new Condition();

    condition.setField(conditionField);

    switch (conditionType) {
      case Between:
        condition.setConstraint(
            Restrictions.between(conditionField, argsIterator.next(), argsIterator.next()));
        break;

      case Equal:
        condition.setConstraint(Restrictions.eq(conditionField, argsIterator.next()));
        break;

      case GreaterThan:
        condition.setConstraint(Restrictions.gt(conditionField, argsIterator.next()));
        break;

      case GreaterThanEqual:
        condition.setConstraint(Restrictions.ge(conditionField, argsIterator.next()));
        break;

      case IsNotNull:
        condition.setConstraint(Restrictions.isNotNull(conditionField));
        break;

      case IsNull:
        condition.setConstraint(Restrictions.isNull(conditionField));
        break;

      case LessThan:
        condition.setConstraint(Restrictions.lt(conditionField, argsIterator.next()));
        break;

      case LessThanEqual:
        condition.setConstraint(Restrictions.le(conditionField, argsIterator.next()));
        break;

      case NotEqual:
        condition.setConstraint(Restrictions.ne(conditionField, argsIterator.next()));
        break;

      case NotWithin:
        condition.setConstraint(
            Restrictions.not(Restrictions.in(conditionField, (Collection) argsIterator.next())));
        break;

      case Within:
        condition.setConstraint(Restrictions.in(conditionField, (Collection) argsIterator.next()));
        break;
    }

    return condition;
  }
  public String scheme() throws WebDataException {
    AdminUser adminUser = getAdminUser();
    if (null == adminUser) {
      throw new WebDataException("你还没有登录!");
    }
    Class<S> cls = kenoService.getSchemeClass();
    if (queryForm != null) {
      if (StringUtils.isNotBlank(queryForm.getPeriodNumber()))
        criteria.add(Restrictions.eq("s.periodNumber", queryForm.getPeriodNumber()));

      if (queryForm.getState() != null)
        criteria.add(Restrictions.eq("s.state", queryForm.getState()));
      if (queryForm.getTicketState() != null)
        criteria.add(Restrictions.eq("s.schemePrintState", queryForm.getTicketState()));

      if (queryForm.getPrizeSended() != null)
        criteria.add(Restrictions.eq("s.cut", queryForm.getPrizeSended()));

      if (queryForm.getWon() != null) criteria.add(Restrictions.eq("s.won", queryForm.getWon()));

      if (StringUtils.isNotBlank(queryForm.getSponsorNames())) {
        String[] arr = queryForm.getSponsorNames().trim().split(",");
        if (arr.length == 1) {
          criteria.add(Restrictions.eq("s.sponsorName", arr[0]));
        } else if (arr.length == 2) {
          criteria.add(
              Restrictions.or(
                  Restrictions.eq("s.sponsorName", arr[0]),
                  Restrictions.eq("s.sponsorName", arr[1])));
        } else {
          criteria.add(Restrictions.in("s.sponsorName", arr));
        }
      }

      if (StringUtils.isNotBlank(queryForm.getSchemeNumbers())) {
        String[] arr = queryForm.getSchemeNumbers().trim().split(",");
        List<Long> idList = new ArrayList<Long>();
        for (String s : arr) {
          Long id = getLottery().getSchemeId(s);
          if (id != null) idList.add(id);
        }
        if (idList.size() == 1) {
          criteria.add(Restrictions.eq("s.id", idList.get(0)));
        } else if (idList.size() == 2) {
          criteria.add(
              Restrictions.or(
                  Restrictions.eq("s.id", idList.get(0)), Restrictions.eq("s.id", idList.get(1))));
        } else if (idList.size() > 2) {
          criteria.add(Restrictions.in("s.id", idList));
        }
      }
    }
    criteria.addOrder(Order.desc("s.id"));
    pagination = kenoService.findByCriteriaAndPagination(criteria, pagination);
    return "scheme";
  }
 /**
  * get an in-restriction. Eventually concatenated with an isNull-restriction if criteria-set
  * contains a null-value.
  *
  * @param criteria criteria to put in in-restriction
  * @param fieldName field-name for in-restriction
  * @return Criterion
  */
 private static Criterion getInRestrictions(
     final Collection<String> criteria, final String fieldName) {
   if (criteria.contains("")) {
     criteria.remove("");
     return criteria.isEmpty()
         ? Restrictions.isNull(fieldName)
         : Restrictions.or(
             Restrictions.isNull(fieldName), Restrictions.in(fieldName, criteria.toArray()));
   } else {
     return Restrictions.in(fieldName, criteria.toArray());
   }
 }
  public List<TaskInstance> findTaskInstances(
      long processInstanceId,
      long tokenId,
      String[] actorIds,
      boolean pooledActors,
      Boolean completed,
      int start,
      int end,
      OrderByComparator orderByComparator) {

    if ((actorIds != null) && (actorIds.length == 0)) {
      return Collections.emptyList();
    }

    try {
      Criteria criteria = _session.createCriteria(TaskInstance.class);

      criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);

      if (processInstanceId > 0) {
        criteria.add(Restrictions.eq("processInstance.id", processInstanceId));
      } else if (tokenId > 0) {
        criteria.add(Restrictions.eq("token.id", tokenId));
      }

      if (actorIds != null) {
        if (pooledActors) {
          Criteria subcriteria = criteria.createCriteria("pooledActors");

          subcriteria.add(Restrictions.in("actorId", actorIds));

          criteria.add(Restrictions.isNull("actorId"));
        } else {
          criteria.add(Restrictions.in("actorId", actorIds));
        }
      }

      if (completed != null) {
        if (completed.booleanValue()) {
          criteria.add(Restrictions.isNotNull("end"));
        } else {
          criteria.add(Restrictions.isNull("end"));
        }
      }

      addPagination(criteria, start, end);
      addOrder(criteria, orderByComparator);

      return criteria.list();
    } catch (Exception e) {
      throw new JbpmException(e);
    }
  }
Exemplo n.º 8
0
    @Override
    public void buildUnordered(Criteria criteria) {

      // Type check
      if (showEventTypesM.getObject().size() < numberOfEventTypes)
        criteria.add(Restrictions.in("type", showEventTypesM.getObject()));
      else log.debug("Not filtering by event type");

      criteria.createAlias("user", "user");

      // Site Check
      List<Site> siteList = showSitesM.getObject();
      if (siteList.size() < numberOfSites || inAPeriod.getObject()) {
        criteria.createAlias("user.periods", "period", JoinType.LEFT_OUTER_JOIN);
        Disjunction siteRestriction = Restrictions.disjunction();
        if (!inAPeriod.getObject())
          siteRestriction.add(Restrictions.isEmpty("user.periods")); // Show users with no periods
        if (!siteList.isEmpty())
          siteRestriction.add(
              Restrictions.in("period.site", siteList)); // Show users with matching periods
        if (inAPeriod.getObject() && siteList.isEmpty()) {
          siteRestriction.add(Restrictions.idEq(-1L)); // Halt query early; don't show anyone.
          criteria.setMaxResults(0);
        }
        criteria.add(siteRestriction);
      } else {
        log.debug("Not filtering by period/site");
      }

      if (fromDateM.getObject() != null && toDateM.getObject() != null) {
        Date startDate = midnightStart(fromDateM.getObject());
        Date endDate = midnightEnd(toDateM.getObject());
        log.debug("Considering events between {} and {}", startDate, endDate);
        criteria.add(Restrictions.between("insertTime", startDate, endDate));
      }

      // set permission check
      if (showPermissionUsers.getObject()) {
        criteria.add(Restrictions.eq("user.permission", true));
      }

      // Also load ResponseData elements in the same query, to avoid thousands of subsequent
      // queries.
      criteria.setFetchMode("responseData", FetchMode.JOIN);

      // The join with periods results in multiple rows for multi-period users.
      // Unfortunately, this confuses the dataprovider, which still counts the duplicates
      // and therefore doesn't return a full page full of items each time.
      criteria.setResultTransformer(
          CriteriaSpecification
              .DISTINCT_ROOT_ENTITY); // Remove duplicate rows as a result of the INNER JOIN
    }
 @SuppressWarnings("unchecked")
 @Override
 public List<GradeOficina> recuperarGradeOficinaPorHorario(
     List<Integer> listaOficinasDisponiveis,
     List<Integer> idsOficinasSelecionadas,
     Integer idHorario) {
   Criteria criteria = getSession().createCriteria(GradeOficina.class);
   if (idsOficinasSelecionadas != null && !idsOficinasSelecionadas.isEmpty()) {
     criteria.add(Restrictions.not(Restrictions.in("oficina.id", idsOficinasSelecionadas)));
   }
   criteria.add(Restrictions.in("oficina.id", listaOficinasDisponiveis));
   criteria.add(Restrictions.eq("horario.id", idHorario));
   return criteria.list();
 }
Exemplo n.º 10
0
  /**
   * A utility method for creating a criteria based on parameters (which are optional)
   *
   * @param whom
   * @param encounters
   * @param questions
   * @param answers
   * @param personTypes
   * @param locations
   * @param sortList
   * @param mostRecentN
   * @param obsGroupId
   * @param fromDate
   * @param toDate
   * @param includeVoidedObs
   * @return
   */
  private Criteria createGetObservationsCriteria(
      List<Person> whom,
      List<Encounter> encounters,
      List<Concept> questions,
      List<Concept> answers,
      List<PERSON_TYPE> personTypes,
      List<Location> locations,
      List<String> sortList,
      Integer mostRecentN,
      Integer obsGroupId,
      Date fromDate,
      Date toDate,
      boolean includeVoidedObs) {
    Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Obs.class, "obs");

    if (CollectionUtils.isNotEmpty(whom)) criteria.add(Restrictions.in("person", whom));

    if (CollectionUtils.isNotEmpty(encounters))
      criteria.add(Restrictions.in("encounter", encounters));

    if (CollectionUtils.isNotEmpty(questions)) criteria.add(Restrictions.in("concept", questions));

    if (CollectionUtils.isNotEmpty(answers)) criteria.add(Restrictions.in("valueCoded", answers));

    if (CollectionUtils.isNotEmpty(personTypes)) getCriteriaPersonModifier(criteria, personTypes);

    if (CollectionUtils.isNotEmpty(locations)) criteria.add(Restrictions.in("location", locations));

    // TODO add an option for each sort item to be asc/desc
    if (CollectionUtils.isNotEmpty(sortList)) {
      for (String sort : sortList) {
        if (sort != null && !"".equals(sort)) criteria.addOrder(Order.desc(sort));
      }
    }

    if (mostRecentN != null && mostRecentN > 0) criteria.setMaxResults(mostRecentN);

    if (obsGroupId != null) {
      criteria.createAlias("obsGroup", "og");
      criteria.add(Restrictions.eq("og.obsId", obsGroupId));
    }

    if (fromDate != null) criteria.add(Restrictions.ge("obsDatetime", fromDate));

    if (toDate != null) criteria.add(Restrictions.le("obsDatetime", toDate));

    if (includeVoidedObs == false) criteria.add(Restrictions.eq("voided", false));
    return criteria;
  }
  /**
   * The 'findConfigurations' function will return a list of configurations based on a search term
   * passed in. The function will search configurations on the following fields configName, orgName
   * and messageTypeName @Table configurations
   *
   * @param searchTerm Will hold the term used search configurations on
   * @return This function will return a list of configuration objects
   */
  @Override
  @SuppressWarnings("unchecked")
  public List<configuration> findConfigurations(String searchTerm) {

    if (searchTerm != "") {
      // get a list of organization id's that match the term passed in
      List<Integer> orgIdList = new ArrayList<Integer>();
      Criteria findOrgs = sessionFactory.getCurrentSession().createCriteria(Organization.class);
      findOrgs.add(Restrictions.like("orgName", "%" + searchTerm + "%"));
      List<Organization> orgs = findOrgs.list();

      for (Organization org : orgs) {
        orgIdList.add(org.getId());
      }

      // get a list of message type id's that match the term passed in
      List<Integer> msgTypeIdList = new ArrayList<Integer>();
      Criteria findMsgTypes = sessionFactory.getCurrentSession().createCriteria(messageType.class);
      findMsgTypes.add(Restrictions.like("name", "%" + searchTerm + "%"));
      List<messageType> msgTypes = findMsgTypes.list();

      for (messageType msgType : msgTypes) {
        msgTypeIdList.add(msgType.getId());
      }

      Criteria criteria = sessionFactory.getCurrentSession().createCriteria(configuration.class);

      if (orgIdList.size() == 0) {
        orgIdList.add(0);
      }
      if (msgTypeIdList.size() == 0) {
        msgTypeIdList.add(0);
      }

      criteria
          .add(
              Restrictions.or(
                  Restrictions.in("orgId", orgIdList),
                  Restrictions.in("messageTypeId", msgTypeIdList)))
          .addOrder(Order.desc("dateCreated"));

      return criteria.list();
    } else {
      Criteria criteria = sessionFactory.getCurrentSession().createCriteria(configuration.class);
      criteria.addOrder(Order.desc("dateCreated"));
      return criteria.list();
    }
  }
Exemplo n.º 12
0
  @Override
  @SuppressWarnings("unchecked")
  public void cleanupDatabase() {
    Criteria allTagEntriesCrit = getSession().createCriteria(RecipeCategoryEntry.class);
    List<RecipeCategoryEntry> usedTagEntries = allTagEntriesCrit.list();

    Set<Long> usedTagIds = new HashSet<Long>();

    for (RecipeCategoryEntry usedTag : usedTagEntries) {
      usedTagIds.add(usedTag.getCategory().getId());
    }

    Criteria unusedTagsCrit = getSession().createCriteria(RecipeCategory.class);
    unusedTagsCrit.add(Restrictions.not(Restrictions.in("id", usedTagIds)));
    unusedTagsCrit.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);

    Criteria allIngrEntriesCrit = getSession().createCriteria(RecipeIngredientEntry.class);
    List<RecipeIngredientEntry> usedIngrEntries = allIngrEntriesCrit.list();

    Set<Long> usedIngrIds = new HashSet<Long>();
    Set<Long> usedIngrGrpIds = new HashSet<Long>();

    for (RecipeIngredientEntry usedIngr : usedIngrEntries) {
      usedIngrIds.add(usedIngr.getIngredient().getId());
      usedIngrGrpIds.add(usedIngr.getGroup().getId());
    }

    Criteria unusedIngrsCrit = getSession().createCriteria(RecipeIngredient.class);
    unusedIngrsCrit.add(Restrictions.not(Restrictions.in("id", usedIngrIds)));
    unusedIngrsCrit.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);

    Criteria unusedIngrGrpsCrit = getSession().createCriteria(RecipeIngredientGroup.class);
    unusedIngrGrpsCrit.add(Restrictions.not(Restrictions.in("id", usedIngrGrpIds)));
    unusedIngrGrpsCrit.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);

    /** ************* */
    for (Object objToDel : unusedTagsCrit.list()) {
      getSession().delete(objToDel);
    }

    for (Object objToDel : unusedIngrsCrit.list()) {
      getSession().delete(objToDel);
    }

    for (Object objToDel : unusedIngrGrpsCrit.list()) {
      getSession().delete(objToDel);
    }
  }
Exemplo n.º 13
0
  @Override
  public int count(ListLogRequest logParam) {
    DetachedCriteria criteria = DetachedCriteria.forClass(Log.class);

    if (StringUtils.isNotBlank(logParam.getLoginName())) {
      criteria.add(Restrictions.eq("loginName", "%" + logParam.getLoginName() + "%"));
    }

    if (logParam.getOperationUsers() != null && logParam.getOperationUsers().length > 0) {
      criteria.add(Restrictions.in("loginName", logParam.getOperationUsers()));
    }

    if (StringUtils.isNotBlank(logParam.getModule())) {
      criteria.add(Restrictions.eq("module", logParam.getModule()));
    }
    if (StringUtils.isNotBlank(logParam.getOperation())) {
      criteria.add(Restrictions.eq("operation", logParam.getOperation()));
    }

    if (logParam.getStartDate() != null) {
      criteria.add(Restrictions.ge("createdOn", logParam.getStartDate()));
    }
    if (logParam.getEndDate() != null) {
      criteria.add(Restrictions.le("createdOn", logParam.getEndDate()));
    }
    return this.countByCriteria(criteria);
  }
Exemplo n.º 14
0
  @Override
  public List<Log> list(ListLogRequest logParam, int pageIndex, int pageSize) {

    DetachedCriteria criteria = DetachedCriteria.forClass(Log.class);

    // TODO 添加大小不敏感
    if (StringUtils.isNotBlank(logParam.getLoginName())) {
      criteria.add(Restrictions.like("loginName", "%" + logParam.getLoginName() + "%"));
    }

    if (logParam.getOperationUsers() != null && logParam.getOperationUsers().length > 0) {
      criteria.add(Restrictions.in("loginName", logParam.getOperationUsers()));
    }
    if (StringUtils.isNotBlank(logParam.getModule())) {
      criteria.add(Restrictions.eq("module", logParam.getModule()));
    }
    if (StringUtils.isNotBlank(logParam.getOperation())) {
      criteria.add(Restrictions.eq("operation", logParam.getOperation()));
    }

    if (logParam.getStartDate() != null) {
      criteria.add(Restrictions.ge("createdOn", logParam.getStartDate()));
    }
    if (logParam.getEndDate() != null) {
      criteria.add(Restrictions.le("createdOn", logParam.getEndDate()));
    }
    criteria.addOrder(Order.desc("createdOn"));

    List result = (List<Log>) findByCriteria(criteria, pageIndex, pageSize);

    return result;
  }
  @Override
  public List<Visiting> getVisitngsToBeCreatedForAnotherThreeMonths() throws Exception {
    Calendar calendar = Calendar.getInstance();
    calendar.add(Calendar.MONTH, -3);
    Date date = calendar.getTime();
    System.out.println("BEFORE THREE MONTHS :" + date);

    String queryString =
        "SELECT visiting_id as visiting_id"
            + " FROM visiting"
            + " WHERE start_date IN (SELECT Max(start_date)"
            + " FROM visiting"
            + " WHERE visiting_status='ACTIVE'"
            + " GROUP BY avg_time_per_appointment, created_user, no_of_patients, hospital_doctor_id, day_of_week)";

    SQLQuery sqlQuery = sessionFactory.getCurrentSession().createSQLQuery(queryString);
    sqlQuery.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);
    List<Map> result = sqlQuery.list();
    List<String> results = new ArrayList<String>();
    for (Map map : result) {
      results.add((String) map.get("visiting_id"));
    }

    Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Visiting.class);
    criteria.add(
        Restrictions.conjunction()
            .add(Restrictions.in("visitingId", results))
            .add(Restrictions.le("startDate", date)));

    return criteria.list();
  }
  /**
   * Loads a list of entities of defined type using their identifiers. The loaded objects are then
   * transformed into Lucene Documents and forwarded to the indexing backend.
   *
   * @param listIds the list of entity identifiers (of type
   * @param session the session to be used
   * @param sessionInitializer the initilization strategies for entities and collections
   * @throws InterruptedException
   */
  private void loadList(
      List<Serializable> listIds, Session session, InstanceInitializer sessionInitializer)
      throws Exception {
    try {
      beginTransaction(session);

      Criteria criteria =
          session
              .createCriteria(type)
              .setCacheMode(cacheMode)
              .setLockMode(LockMode.NONE)
              .setCacheable(false)
              .setFlushMode(FlushMode.MANUAL)
              .setFetchSize(listIds.size())
              .setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY)
              .add(Restrictions.in(idName, listIds));
      List<?> list = criteria.list();
      monitor.entitiesLoaded(list.size());
      indexAllQueue(session, list, sessionInitializer);
      session.clear();
    } finally {
      // it's read-only, so no need to commit
      rollbackTransaction(session);
    }
  }
Exemplo n.º 17
0
  public List<Sample> list(Cycle cycle) {
    List<Sample> lista = null;
    try {
      VisitDAO vDAo = new VisitDAO();
      List<Visit> lVisit = vDAo.list(cycle);

      this.setSessao(HibernateUtil.getSessionFactory().openSession());
      setTransacao(getSessao().beginTransaction());
      lista =
          this.getSessao()
              .createCriteria(Sample.class)
              .add(Restrictions.in("visit", lVisit))
              .addOrder(Order.desc("id"))
              .list();

    } catch (Throwable e) {
      if (getTransacao().isActive()) {
        getTransacao().rollback();
      }
      System.out.println("Não foi possível listar: " + e.getMessage());
    } finally {
      getSessao().close();
    }
    return lista;
  }
Exemplo n.º 18
0
  @Override
  public Long verificarConflitoHorario(Horario model) {
    Criteria criteria = getSession().createCriteria(Horario.class);

    // Removendo da pesquisa o proprio registro quando for edição
    if (model.getId() != null && !model.getId().equals(0)) {
      List<Integer> listaIds = new ArrayList<Integer>();
      listaIds.add(model.getId());
      criteria.add(Restrictions.not(Restrictions.in("id", listaIds)));
    }

    criteria.add(Restrictions.eq("curso.id", model.getCurso().getId()));
    criteria.add(
        Restrictions.or(
            Restrictions.or(
                Restrictions.between(
                    "datHoraInicio", model.getDatHoraInicio(), model.getDatHoraFim()),
                Restrictions.between(
                    "datHoraFim", model.getDatHoraInicio(), model.getDatHoraFim())),
            Restrictions.and(
                Restrictions.and(
                    Restrictions.le("datHoraInicio", model.getDatHoraInicio()),
                    Restrictions.ge("datHoraFim", model.getDatHoraInicio())),
                Restrictions.and(
                    Restrictions.le("datHoraInicio", model.getDatHoraFim()),
                    Restrictions.ge("datHoraFim", model.getDatHoraFim())))));
    criteria.setProjection(Projections.rowCount());

    Long result = (Long) criteria.list().get(0);
    return result;
  }
Exemplo n.º 19
0
  /**
   * Actualiza los estados de las incidencias que NO se encuentren en el array y cuyo estado no es
   * ya el pasado como parámetro.
   *
   * @param idsIncidencias Array de ids de incidencias
   * @param estado Estado a establecer
   */
  @Transactional(
      propagation = Propagation.REQUIRES_NEW,
      readOnly = false,
      rollbackFor = Throwable.class)
  public void updateEstadosIncidencias(Long[] idsIncidencias, String estado) {

    if (idsIncidencias != null && idsIncidencias.length > 0) {
      EstadoIncidencia estadoObj = getEstadoIncidenciaByIdentificador(estado);
      if (estado != null) {
        Criteria crit =
            getSession()
                .createCriteria(Incidencia.class)
                .add(Restrictions.not(Restrictions.in("id", idsIncidencias)))
                .add(Restrictions.ne("estado", estadoObj));

        List<Incidencia> resultado = crit.list();
        for (Incidencia inc : resultado) {
          if (log.isTraceEnabled()) {
            log.trace("Actualizamos el estado de la incidencia " + inc.getId() + " a " + estado);
          }
          inc.setEstado(estadoObj);
          getSession().update(inc);
        }
      } else {
        log.error("El estado " + estado + " no se encuentra en la base de datos");
      }
    }
  }
Exemplo n.º 20
0
 @Override
 public List<Participation> getMarkersAvailableParticipations(Group group) {
   if (group.getTutors().size() > 0) {
     Integer[] ids = new Integer[group.getTutors().size()];
     int i = 0;
     for (Participation participation : group.getTutors()) {
       ids[i++] = participation.getId();
     }
     return getSession()
         .createCriteria(Participation.class)
         .add(Restrictions.eq("lecture", group.getLecture()))
         .add(
             Restrictions.or(
                 Restrictions.eq("role", ParticipationRole.TUTOR.toString()),
                 Restrictions.eq("role", ParticipationRole.ADVISOR.toString())))
         .add(Restrictions.not(Restrictions.in("id", ids)))
         .createCriteria("user")
         .addOrder(Order.asc("lastName"))
         .addOrder(Order.asc("firstName"))
         .list();
   } else {
     return getSession()
         .createCriteria(Participation.class)
         .add(Restrictions.eq("lecture", group.getLecture()))
         .add(
             Restrictions.or(
                 Restrictions.eq("role", ParticipationRole.TUTOR.toString()),
                 Restrictions.eq("role", ParticipationRole.ADVISOR.toString())))
         .createCriteria("user")
         .addOrder(Order.asc("lastName"))
         .addOrder(Order.asc("firstName"))
         .list();
   }
 }
  @Override
  @SuppressWarnings("unchecked")
  public List<ProgramInstance> getByStatus(
      ProgramStatus status,
      Program program,
      Collection<Integer> orgunitIds,
      Date startDate,
      Date endDate,
      Integer min,
      Integer max) {
    Criteria criteria =
        getCriteria(
                Restrictions.eq("program", program),
                Restrictions.between("enrollmentDate", startDate, endDate))
            .createAlias("entityInstance", "entityInstance")
            .createAlias("entityInstance.organisationUnit", "organisationUnit")
            .add(Restrictions.in("organisationUnit.id", orgunitIds))
            .add(Restrictions.eq("status", status));

    if (min != null) {
      criteria.setFirstResult(min);
    }

    if (max != null) {
      criteria.setMaxResults(max);
    }

    return criteria.list();
  }
Exemplo n.º 22
0
 @Override
 public List<DeclarationRecordChild> listDeclarationChildrendContainingEstate(
     DictEstate dictEstate) {
   Criteria listCriteria = getSession().createCriteria(DeclarationRecordChild.class);
   listCriteria.add(Restrictions.in("estate", new DictEstate[] {dictEstate}));
   return listCriteria.list();
 }
Exemplo n.º 23
0
  protected XDetachedCriteria buildListDetachedCriteria() {
    XDetachedCriteria criteria = new XDetachedCriteria(this.passcountClass, "m");
    if (queryForm != null) {
      if (0 != queryForm.getPeriodId())
        criteria.add(Restrictions.eq("m.periodId", queryForm.getPeriodId()));
      if (queryForm.getMode() != null) criteria.add(Restrictions.eq("m.mode", queryForm.getMode()));

      if (queryForm.getShareType() != null)
        criteria.add(Restrictions.eq("m.shareType", queryForm.getShareType()));

      if (queryForm.getState() != null)
        criteria.add(Restrictions.eq("m.state", queryForm.getState()));

      if (StringUtils.isNotBlank(queryForm.getSponsorNames())) {
        String[] arr = queryForm.getSponsorNames().trim().split(",");
        if (arr.length == 1) {
          criteria.add(Restrictions.eq("m.sponsorName", arr[0]));
        } else if (arr.length == 2) {
          criteria.add(
              Restrictions.or(
                  Restrictions.eq("m.sponsorName", arr[0]),
                  Restrictions.eq("m.sponsorName", arr[1])));
        } else {
          criteria.add(Restrictions.in("m.sponsorName", arr));
        }
      }
    }
    this.addDetachedCriteria(criteria);
    return criteria;
  }
Exemplo n.º 24
0
  @Override
  @Transactional(readOnly = true)
  public AnnotationView[] listAnnotationsNoReplies(
      final Long articleID,
      final Set<AnnotationType> annotationTypes,
      final AnnotationOrder order) {
    if (order == AnnotationOrder.MOST_RECENT_REPLY) {
      throw new IllegalArgumentException(
          "Cannot specify Most Recent Reply order type when replies are not being loaded up");
    }
    // Basic criteria
    DetachedCriteria criteria =
        DetachedCriteria.forClass(Annotation.class)
            .add(Restrictions.eq("articleID", articleID))
            .setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
    // restrict by type
    if (annotationTypes != null && !annotationTypes.isEmpty()) {
      criteria.add(Restrictions.in("type", annotationTypes));
    }
    switch (order) {
      case OLDEST_TO_NEWEST:
        criteria.addOrder(Order.asc("created"));
        break;
      case NEWEST_TO_OLDEST:
        criteria.addOrder(Order.desc("created"));
        break;
    }
    List annotationResults = hibernateTemplate.findByCriteria(criteria);
    // Don't want to call buildAnnotationView() here because that would involve finding the article
    // title and doi for each annotation,
    // when we only need to do it once. So load up the info we need to build annotation views here
    Object[] articleTitleAndDoi;
    try {
      articleTitleAndDoi =
          (Object[])
              hibernateTemplate
                  .findByCriteria(
                      DetachedCriteria.forClass(Article.class)
                          .add(Restrictions.eq("ID", articleID))
                          .setProjection(
                              Projections.projectionList()
                                  .add(Projections.property("doi"))
                                  .add(Projections.property("title"))),
                      0,
                      1)
                  .get(0);

    } catch (IndexOutOfBoundsException e) {
      throw new IllegalArgumentException("article " + articleID + " didn't exist");
    }
    String articleDoi = (String) articleTitleAndDoi[0];
    String articleTitle = (String) articleTitleAndDoi[1];

    List<AnnotationView> viewResults = new ArrayList<AnnotationView>(annotationResults.size());
    for (Object annotation : annotationResults) {
      viewResults.add(new AnnotationView((Annotation) annotation, articleDoi, articleTitle, null));
    }
    return viewResults.toArray(new AnnotationView[viewResults.size()]);
  }
Exemplo n.º 25
0
  protected void addSearchByUserRolesCriterion(
      Criteria criteria, Boolean searchByUserRoles, ServiceContext serviceContext)
      throws SystemException {

    if (searchByUserRoles == null) {
      return;
    }

    Criteria assigneesCriteria = criteria.createCriteria("assignees");

    if (!searchByUserRoles) {
      assigneesCriteria.add(Restrictions.eq("assigneeClassName", User.class.getName()));
      assigneesCriteria.add(Restrictions.eq("assigneeClassPK", serviceContext.getUserId()));

      return;
    }

    List<Long> roleIds = RoleRetrievalUtil.getRoleIds(serviceContext);

    List<UserGroupRole> userGroupRoles =
        UserGroupRoleLocalServiceUtil.getUserGroupRoles(serviceContext.getUserId());

    if (userGroupRoles.isEmpty()) {
      assigneesCriteria.add(Restrictions.eq("assigneeClassName", Role.class.getName()));
      assigneesCriteria.add(
          Restrictions.in("assigneeClassPK", roleIds.toArray(new Long[roleIds.size()])));
    } else {
      Junction junction = Restrictions.disjunction();

      junction.add(
          Restrictions.and(
              Restrictions.eq("assigneeClassName", Role.class.getName()),
              Restrictions.in("assigneeClassPK", roleIds.toArray(new Long[roleIds.size()]))));

      for (UserGroupRole userGroupRole : userGroupRoles) {
        junction.add(
            Restrictions.and(
                Restrictions.eq("groupId", userGroupRole.getGroupId()),
                Restrictions.and(
                    Restrictions.eq("assigneeClassName", Role.class.getName()),
                    Restrictions.eq("assigneeClassPK", userGroupRole.getRoleId()))));
      }

      assigneesCriteria.add(junction);
    }
  }
Exemplo n.º 26
0
 public static Criterion in(String propertyName, Collection<?> values, int maxLength) {
   if (maxLength < 1) throw new IllegalArgumentException("maxLength must be positive");
   Disjunction result = Restrictions.disjunction();
   for (Collection<?> part : partitionCollection(values, maxLength)) {
     result.add(Restrictions.in(propertyName, part));
   }
   return result;
 }
Exemplo n.º 27
0
 @Override
 @SuppressWarnings("unchecked")
 public Collection<Message> getMessagesByStatus(MessageStatus... statuses) {
   return getCurrentSession()
       .createCriteria(Message.class)
       .add(Restrictions.in("status", statuses))
       .list();
 }
Exemplo n.º 28
0
  /*
   * (non-Javadoc)
   *
   * @see com.changpeng.common.action.AbstractAction#go()
   */
  @Override
  protected String go() throws Exception {
    this.lawyer = this.getLoginUser();
    // TODO Auto-generated method stub
    BasicService basic = (BasicService) getBean("basicService");
    DetachedCriteria detachedCriteria = DetachedCriteria.forClass(Articles.class);
    detachedCriteria.add(Restrictions.eq("type", type));

    if (type == 1) { // 重要通知才搞这个。那个什么帮助就都显示了
      // Criterion province = Restrictions.eq("provinceid",
      // this.getLoginUser().getProvinceid());

      int directunion = this.getLoginUser().getDirectunion();
      SysGroup group = (SysGroup) basic.get(SysGroup.class, directunion);

      detachedCriteria.add(Restrictions.eq("status", 0));
      // 显示我的事务所的通知,显示我的律协的通知,显示我的省律协的通知,显示系统的通只
      // detachedCriteria.add(Restrictions.in("thegroup", new Integer[] {
      // this.getLoginUser().getProvinceunion(),
      // this.getLoginUser().getDirectunion(),
      // this.getLoginUser().getTheoffice(), 0 }));

      Criterion province =
          Restrictions.in(
              "thegroup",
              new Integer[] {
                this.getLoginUser().getProvinceunion(),
                this.getLoginUser().getDirectunion(),
                this.getLoginUser().getTheoffice(),
                0
              });

      Criterion c = Restrictions.eq("provinceid", 0);
      detachedCriteria.add(Restrictions.or(c, province));

      detachedCriteria.addOrder(Order.desc("createtime"));
    }

    // 按现实顺序来
    detachedCriteria.addOrder(Order.desc("listorder"));
    detachedCriteria.addOrder(Order.desc("createtime"));

    this.page = basic.findPageByCriteria(detachedCriteria, pageSize, pageNo);

    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.DATE, -1); // 得到前一天
    cal.add(Calendar.MONTH, -1); // 得到前一个月
    long date = cal.getTimeInMillis();
    System.out.println(date);
    // long lastdaya=df.format(new java.util.Date(date));
    // System.out.println(lastdaya);
    lastday = new Timestamp(date);
    System.out.println(lastday);

    // TODO Auto-generated method stub
    return SUCCESS;
  }
Exemplo n.º 29
0
  public int countTaskInstances(
      long processInstanceId,
      long tokenId,
      String[] actorIds,
      boolean pooledActors,
      Boolean completed) {

    if ((actorIds != null) && (actorIds.length == 0)) {
      return 0;
    }

    try {
      Criteria criteria = _session.createCriteria(TaskInstance.class);

      criteria.setProjection(Projections.countDistinct("id"));

      if (processInstanceId > 0) {
        criteria.add(Restrictions.eq("processInstance.id", processInstanceId));
      } else if (tokenId > 0) {
        criteria.add(Restrictions.eq("token.id", tokenId));
      } else if (actorIds != null) {
        if (pooledActors) {
          Criteria subcriteria = criteria.createCriteria("pooledActors");

          subcriteria.add(Restrictions.in("actorId", actorIds));
        } else {
          criteria.add(Restrictions.in("actorId", actorIds));
        }
      }

      if (completed != null) {
        if (completed.booleanValue()) {
          criteria.add(Restrictions.isNotNull("end"));
        } else {
          criteria.add(Restrictions.isNull("end"));
        }
      }

      Number count = (Number) criteria.uniqueResult();

      return count.intValue();
    } catch (Exception e) {
      throw new JbpmException(e);
    }
  }
  @Override
  @SuppressWarnings("unchecked")
  public List<ProgramInstance> get(Collection<Program> programs) {
    if (programs == null || programs.isEmpty()) {
      return new ArrayList<>();
    }

    return getCriteria(Restrictions.in("program", programs)).list();
  }