@SuppressWarnings({"unchecked", "rawtypes"})
  @Override
  public List<Lista> getByQuery(Map<String, Object> m) throws DataException {
    Criteria crit = this.getSession().createCriteria(Lista.class);

    /** Extraemos el mapa de parametros. */
    Iterator it = m.entrySet().iterator();
    while (it.hasNext()) {
      Map.Entry e = (Map.Entry) it.next();
      if (e.getKey().equals("descripcion"))
        crit.add(
            Restrictions.sqlRestriction("trim(ucase(descripcion)) like '%" + e.getValue() + "%'"));
      if (e.getKey().equals("borrado"))
        crit.add(Restrictions.sqlRestriction("borrado=" + e.getValue()));
      if (e.getKey().equals("idUsuario"))
        crit.add(Restrictions.sqlRestriction("idUsuario=" + e.getValue()));
    }

    // reemplazar por la linea de arriba las dos siguientes si se requiere ordenacion
    // Si en vez de Criteria es un SQLQuery echa un vistazo a la clase del proyecto compras-rest
    // ProveedorMercanciaDAOImpl
    Criteria criteriaConOrder = asignarOrdenacionACriteria(crit);
    List<Lista> list = criteriaConOrder.list();
    return list;
  }
  @GlobalDBOpenCloseAndUserPrivilages
  public Map getUserTypeSize(
      Session session,
      HttpServletRequest request,
      HttpServletResponse response,
      String LoggedInRegion,
      String LoggedInUser) {
    Map resultMap = new HashMap();
    String isAccountModule = "No";
    Map financialYearMap = new LinkedHashMap();
    financialYearMap.put("0", "--Select--");
    UserViewModel userObj = (UserViewModel) request.getSession(false).getAttribute("userDetails");

    Criteria rcCriteria = session.createCriteria(Useroperatingrights.class);
    rcCriteria.add(Restrictions.sqlRestriction("userid = '" + userObj.getUserid() + "'"));
    rcCriteria.add(Restrictions.sqlRestriction("accessright is true"));
    rcCriteria.addOrder(Order.asc("usertypeid"));
    List rcList = rcCriteria.list();
    resultMap.put("typesize", rcList.size());

    Criteria fyearsCriteria = session.createCriteria(Accountingyear.class);
    List fyearsList = fyearsCriteria.list();
    if (fyearsList.size() > 0) {
      for (int i = 0; i < fyearsList.size(); i++) {
        Accountingyear accountingyearObj = (Accountingyear) fyearsList.get(i);
        financialYearMap.put(
            accountingyearObj.getId(),
            (accountingyearObj.getStartyear() + "-" + accountingyearObj.getEndyear()));
      }
    }
    resultMap.put("financialYearMap", financialYearMap);

    if (rcList.size() == 1) {
      Useroperatingrights useroperatingrightsObj = (Useroperatingrights) rcList.get(0);

      Criteria privileageCriteria = session.createCriteria(Menuprivilages.class);
      privileageCriteria.add(
          Restrictions.sqlRestriction("usertype = " + useroperatingrightsObj.getUsertypeid()));
      privileageCriteria.add(Restrictions.sqlRestriction("accessright is true"));
      List privileageList = privileageCriteria.list();
      if (privileageList.size() > 0) {
        for (int j = 0; j < privileageList.size(); j++) {
          Menuprivilages menuprivilagesObj = (Menuprivilages) privileageList.get(j);
          //
          // System.out.println("menuprivilagesObj.getMenumaster().getGrouptype()==" +
          // menuprivilagesObj.getMenumaster().getGrouptype());
          if (menuprivilagesObj.getMenumaster().getGrouptype() == null) {
          } else if (menuprivilagesObj.getMenumaster().getGrouptype() == 'A') {
            isAccountModule = "Yes";
            break;
          }
        }
      }
    }
    resultMap.put("isAccountModule", isAccountModule);

    return resultMap;
  }
  @GlobalDBOpenCloseAndUserPrivilages
  public Map loadRegionDetails(
      Session session,
      HttpServletRequest request,
      HttpServletResponse response,
      String LoggedInRegion,
      String LoggedInUser) {
    Map resultMap = new HashMap();
    Map regionMap = new LinkedHashMap();
    regionMap.put("0", "----Select One----");
    String regionid = "";
    String regionname = "";
    try {
      Criteria rgnCrit = session.createCriteria(Regionmaster.class);
      rgnCrit.add(Restrictions.sqlRestriction("defaultregion is true"));
      rgnCrit.addOrder(Order.asc("regionname"));
      List<Regionmaster> rgnList = rgnCrit.list();
      resultMap = new TreeMap();
      for (Regionmaster lbobj : rgnList) {

        regionid = lbobj.getId();
        regionname = lbobj.getRegionname();

        regionMap.put(regionid, regionname);
      }

      resultMap.put("regionlist", regionMap);

    } catch (Exception e) {
      e.printStackTrace();
    }
    return resultMap;
  }
 public Criterion transform(IRestriction source) {
   if (source instanceof SqlRestriction) {
     SqlRestriction sqlRestriction = (SqlRestriction) source;
     return Restrictions.sqlRestriction(sqlRestriction.getSql());
   }
   return null;
 }
 /** {@inheritDoc} */
 @Override
 public Criterion getCriterion() {
   return Restrictions.sqlRestriction(
       " {alias}.ifserviceid NOT IN (SELECT DISTINCT ifservices.id FROM ifservices, ipinterface, node WHERE ifservices.ipinterfaceid = ipinterface.id AND ipinterface.nodeid = node.nodeid AND node.foreignSource=?)",
       getValue(),
       StringType.INSTANCE);
 }
  @GlobalDBOpenCloseAndUserPrivilages
  public Map getUsertypesforModify1(
      Session session,
      HttpServletRequest request,
      HttpServletResponse response,
      String LoggedInRegion,
      String LoggedInUser,
      String usertypeid) {
    Map resultMap = new HashMap();
    Map usertypeMap = new LinkedHashMap();
    usertypeMap.put("0", "--Select--");
    try {
      Criteria usertypeCrit = session.createCriteria(Usertype.class);
      usertypeCrit.add(Restrictions.sqlRestriction("parentcode=" + Integer.parseInt(usertypeid)));
      usertypeCrit.addOrder(Order.asc("id"));
      List<Usertype> usertypeList = usertypeCrit.list();
      resultMap = new TreeMap();
      for (Usertype lbobj : usertypeList) {
        usertypeMap.put(lbobj.getId(), lbobj.getUsertypename());
      }
      resultMap.put("usertypes", usertypeMap);

    } catch (Exception e) {
      e.printStackTrace();
    }
    return resultMap;
  }
  /**
   * This method is for getting all Presenter
   *
   * @param requestParamters
   * @return Presenter List
   */
  public ArrayList getAllPresenter(HttpServletRequest req) {

    log.log(Level.INFO, "PresenterMaintanence --> getAllPresenter");
    ArrayList arrActivity = new ArrayList();
    Session session = null;
    int month = Calendar.getInstance().get(Calendar.MONTH) + 1;
    int year = Calendar.getInstance().get(Calendar.YEAR);
    User userObj = (User) req.getSession().getAttribute("currUserObj");
    try {

      session = HibernateFactory.openSession();
      Criteria crit = session.createCriteria(Presenter.class);
      crit.add(Restrictions.sqlRestriction("MONTH(START_DATE)=?", month, Hibernate.INTEGER));
      crit.add(Restrictions.sqlRestriction("YEAR(START_DATE)=?", year, Hibernate.INTEGER));
      crit.add(Restrictions.eq("status", true));

      if (userObj.isBuLevel() && userObj.getBuCode() != 0) {
        crit.add(Restrictions.eq("buCode", userObj.getBuCode()));
      }
      if (userObj.isDistrictLevel()) {
        crit.add(Restrictions.eq("distCode", userObj.getDistrict()));
      }
      if (userObj.isBranchLevel()) {
        crit.add(Restrictions.eq("branchCode", userObj.getBranchCode()));
      }
      if (userObj.isCityLevel()) {
        crit.add(Restrictions.eq("cityCode", userObj.getCityCode()));
      }
      if (userObj.isSscLevel()) {
        crit.add(Restrictions.eq("sscCode", userObj.getSscCode()));
      }
      if (userObj.isOfficeLevel()) {
        crit.add(Restrictions.eq("officeCode", userObj.getOfficeCode()));
      }

      arrActivity = (ArrayList) crit.list();

    } catch (Exception e) {
      log.log(Level.SEVERE, e.getMessage());
      e.printStackTrace();
    } finally {
      HibernateFactory.close(session);
    }

    return arrActivity;
  }
 /*
  * (non-Javadoc)
  * @see cn.trymore.core.dao.DAOGeneric#getListByCriteria(org.hibernate.criterion.DetachedCriteria, boolean)
  */
 @SuppressWarnings("unchecked")
 public List<T> getListByCriteria(final DetachedCriteria criteria, final boolean dataFilter)
     throws DAOException {
   if (dataFilter && UtilString.isNotEmpty(this.getQueryFilter())) {
     criteria.add(Restrictions.sqlRestriction(this.getQueryFilter()));
     this.setQueryFilter(null);
   }
   return (List<T>) getHibernateTemplate().findByCriteria(criteria);
 }
 @SuppressWarnings("unchecked")
 @Override
 public List<NoticeModel> getNotices(String userId, String beginDate, String endDate, String type)
     throws ServiceException {
   // TODO Auto-generated method stub
   DetachedCriteria criteria = DetachedCriteria.forClass(NoticeModel.class);
   if (StringUtils.isNotEmpty(userId) && (!userId.equals("1"))) {
     criteria.add(Restrictions.like("teacherAttendIds", userId, MatchMode.ANYWHERE));
   }
   if (StringUtils.isNotEmpty(beginDate))
     criteria.add(Restrictions.sqlRestriction("postTime >= '" + beginDate + " 00:00:00'"));
   if (StringUtils.isNotEmpty(endDate))
     criteria.add(Restrictions.sqlRestriction("postTime <= '" + endDate + " 23:59:59'"));
   if (StringUtils.isNotEmpty(type)) criteria.add(Restrictions.eq("type", type));
   criteria.add(Restrictions.eq("status", NoticeModel.EStatus.Published.getValue()));
   criteria.addOrder(Order.desc("postTime"));
   return noticeDAO.getListByCriteria(criteria);
 }
  @GlobalDBOpenCloseAndUserPrivilages
  public Map getAssignedMenus(
      Session session,
      HttpServletRequest request,
      HttpServletResponse response,
      String LoggedInRegion,
      String LoggedInUser,
      String usertypes) {
    Map resultMap = new HashMap();
    Map menuMap = new LinkedHashMap();
    try {
      Criteria menuCrit = session.createCriteria(Menuprivilages.class);
      menuCrit.add(Restrictions.sqlRestriction("usertype=" + Integer.parseInt(usertypes)));
      menuCrit.add(Restrictions.sqlRestriction("accessright is true"));
      List menuList = menuCrit.list();
      if (menuList.size() > 0) {
        for (int i = 0; i < menuList.size(); i++) {
          Menuprivilages menuObj = (Menuprivilages) menuList.get(i);

          Criteria criteria = session.createCriteria(Menumaster.class);
          criteria.add(Restrictions.ne("parentcode", 0));
          criteria.add(Restrictions.eq("code", menuObj.getMenumaster().getCode()));
          criteria.add(Restrictions.ne("methodname", ""));
          //                        criteria.add(Restrictions.sqlRestriction("code=" +
          // menuObj.getMenumaster().getCode()+" and parentcode!=0"));
          List menulist = criteria.list();
          if (menulist.size() > 0) {
            menuMap.put(
                "accessright" + menuObj.getMenumaster().getCode(),
                "accessright" + menuObj.getMenumaster().getCode());
          }
        }
        resultMap.put("menuMap", menuMap);
      } else {
        resultMap.put("ERROR", "Not Assigned");
      }

    } catch (Exception e) {
    }

    return resultMap;
  }
  public void insertParent(Session session, int menuId, int usertypes) {
    Transaction transaction = null;
    try {
      Criteria menuCrit = session.createCriteria(Menumaster.class);
      menuCrit.add(Restrictions.sqlRestriction("code=" + menuId));
      List menuList = menuCrit.list();
      if (menuList.size() > 0) {
        Menumaster menuObj = (Menumaster) menuList.get(0);

        Criteria menuCrit1 = session.createCriteria(Menuprivilages.class);
        menuCrit1.add(Restrictions.sqlRestriction("usertype=" + usertypes));
        menuCrit1.add(Restrictions.sqlRestriction("menumaster=" + menuObj.getParentcode()));
        List menuList1 = menuCrit1.list();
        if (menuList1.size() <= 0) {
          transaction = session.beginTransaction();

          Usertype typeobj = new Usertype();
          typeobj.setId(usertypes);

          Menumaster menuMasterObj = new Menumaster();
          menuMasterObj.setCode(menuObj.getParentcode());

          Menuprivilages menuObj2 = new Menuprivilages();
          menuObj2.setId(String.valueOf(getSequenceNumber(session)));
          menuObj2.setUsertype(typeobj);
          menuObj2.setMenumaster(menuMasterObj);
          menuObj2.setAccessright(Boolean.TRUE);
          session.save(menuObj2);
          transaction.commit();

          this.insertParent(session, menuObj.getParentcode(), usertypes);
        }
      }
    } catch (Exception e) {
      if (transaction != null) {
        transaction.rollback();
      }
      e.printStackTrace();
    }
  }
  public void testQueryView() {

    User entity = new User();
    entity.setStatus("NONEOCT");

    GeneralCriteria criteria = new GeneralCriteria(UserVO.class);
    criteria.setDataOnly(false);
    criteria.addOrder(Order.desc("activeTime"));
    if (entity != null) {
      if (entity.getUsername() != null) {
        criteria.add(Restrictions.eq("username", entity.getUsername()));
      }
      if (entity.getPassword() != null) {
        criteria.add(Restrictions.eq("bindIP", entity.getBindIP()));
      }
      if (entity.getStatus() != null) {
        if (entity.getStatus().equals("NORMAL")) { // 正常
          criteria.add(Restrictions.eq("status", "NORMAL"));
        } else if (entity.getStatus().equals("EXPIRED")) { // 过期
          criteria.add(Restrictions.gt("expiredTime", new Date()));
        } else if (entity.getStatus().equals("NONEOCT")) { // 无流量
          criteria.add(
              Restrictions.sqlRestriction("maxOctets*1024*1024>sumInputOctets+sumOutputOctets"));
        }
      }
    }
    GeneralCriteriaResult<UserVO> result = criteria.executeQuery();
    GeneralCriteriaQuery query = criteria.getCriteriaQuery();
    System.out.println("结果数:" + result.getTotal());
    Calendar c = Calendar.getInstance();
    c.clear();
    c.set(2012, 6, 1);
    Date start = c.getTime();
    c.add(Calendar.MONTH, 12);
    Date end = c.getTime();
    DecimalFormat df = new DecimalFormat(".00");
    for (UserVO vo : result.getData()) {
      System.out.println(vo.getId() + ",username:"******",sumoct:");
      User u = (User) query.get(User.class, vo.getId());

      // UserFeeCycle cycle = new UserFeeCycle();
      //			cycle.setStart(start);
      //			cycle.setEnd(end);

      // double ratio = vo.getActualFee()/(vo.getMaxOctets()*1024);
      // cycle.setCostFee(Double.valueOf(df.format(((cycle.getInputOct()+cycle.getOutputOct())*1.05/1024)*ratio)));
      // cycle.setUser(u);
      // query.save(cycle);
    }
  }
  public void updateParent(Session session, int menuId, int usertypes) {
    Transaction transaction = null;
    try {
      Criteria menuCrit3 = session.createCriteria(Menuprivilages.class);
      menuCrit3.add(Restrictions.sqlRestriction("usertype=" + usertypes));
      menuCrit3.add(Restrictions.sqlRestriction("menumaster=" + menuId));
      List menuList3 = menuCrit3.list();
      if (menuList3.size() > 0) {
        transaction = session.beginTransaction();
        Menuprivilages menuObj3 = (Menuprivilages) menuList3.get(0);
        menuObj3.setAccessright(Boolean.TRUE);
        session.update(menuObj3);
        transaction.commit();

        this.updateParent(session, menuObj3.getMenumaster().getParentcode(), usertypes);
      }
    } catch (Exception e) {
      if (transaction != null) {
        transaction.rollback();
      }
      e.printStackTrace();
    }
  }
Exemple #14
0
 @Override
 public List<Participation> getParticipationsWithNoSubmissionToTaskOrdered(Task task) {
   return getSession()
       .createCriteria(Participation.class)
       .add(Restrictions.eq("lecture", task.getTaskGroup().getLecture()))
       .add(
           Restrictions.sqlRestriction(
               "{alias}.id not in (SELECT submitters_id FROM submissions, submissions_participations where submissions.submissionid=submissions_participations.submissions_submissionid and taskid="
                   + task.getTaskid()
                   + ")"))
       .createCriteria("user")
       .addOrder(Order.asc("lastName"))
       .addOrder(Order.asc("firstName"))
       .list();
 }
  @SuppressWarnings("unchecked")
  @Override
  public List<CourseProductItemModel> getProductsByCourse(String course) {
    // TODO Auto-generated method stub
    DetachedCriteria criteria = DetachedCriteria.forClass(CourseProductItemModel.class);
    criteria.add(Restrictions.sqlRestriction("course_name=?", course, Hibernate.STRING));

    try {
      List<CourseProductItemModel> list = courseProductConfigDAO.getListByCriteria(criteria);
      courseProductConfigDAO.saveOrUpdate(list, false);
      return courseProductConfigDAO.getListByCriteria(criteria);
    } catch (DAOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      return null;
    }
  }
  /*
   * (non-Javadoc)
   * @see cn.trymore.core.dao.DAOGeneric#findPageByCriteria(org.hibernate.criterion.DetachedCriteria, int, int, boolean)
   */
  @SuppressWarnings({"unchecked"})
  public PaginationSupport<T> findPageByCriteria(
      final DetachedCriteria criteria,
      final int pageSize,
      final int startIndex,
      final boolean dataFilter)
      throws DAOException {
    if (dataFilter && UtilString.isNotEmpty(this.getQueryFilter())) {
      criteria.add(Restrictions.sqlRestriction(this.getQueryFilter()));
      this.setQueryFilter(null);
    }

    return (PaginationSupport<T>)
        getHibernateTemplate()
            .execute(
                new HibernateCallback() {
                  public Object doInHibernate(Session session)
                      throws HibernateException, SQLException {
                    Criteria execCriteria = criteria.getExecutableCriteria(session);

                    int rowCount =
                        ((Integer)
                                execCriteria.setProjection(Projections.rowCount()).uniqueResult())
                            .intValue();
                    execCriteria.setProjection(null);
                    execCriteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
                    // execCriteria.setResultTransformer(CriteriaSpecification.ROOT_ENTITY);
                    execCriteria.setFirstResult(startIndex);

                    if (pageSize > 0) {
                      execCriteria.setMaxResults(pageSize);
                    } else {
                      execCriteria.setMaxResults(rowCount);
                    }
                    List<T> items = execCriteria.list();
                    return rowCount > 0
                        ? new PaginationSupport<T>(
                            items, rowCount, startIndex, pageSize > 0 ? pageSize : rowCount)
                        : null;
                  }
                });
  }
Exemple #17
0
 public void sql(String sql, Object objects, Type type) {
   Restrictions.sqlRestriction(sql, objects, type);
 }
Exemple #18
0
 public void sql(String sql) {
   Restrictions.sqlRestriction(sql);
 }
Exemple #19
0
  @Override
  public Iterator<Item> findByMetadataQuery(
      Context context,
      List<List<MetadataField>> listFieldList,
      List<String> query_op,
      List<String> query_val,
      List<UUID> collectionUuids,
      String regexClause,
      int offset,
      int limit)
      throws SQLException {
    Criteria criteria = createCriteria(context, Item.class, "item");
    criteria.setFirstResult(offset);
    criteria.setMaxResults(limit);

    if (!collectionUuids.isEmpty()) {
      DetachedCriteria dcollCriteria = DetachedCriteria.forClass(Collection.class, "coll");
      dcollCriteria.setProjection(Projections.property("coll.id"));
      dcollCriteria.add(Restrictions.eqProperty("coll.id", "item.owningCollection"));
      dcollCriteria.add(Restrictions.in("coll.id", collectionUuids));
      criteria.add(Subqueries.exists(dcollCriteria));
    }

    int index = Math.min(listFieldList.size(), Math.min(query_op.size(), query_val.size()));
    StringBuilder sb = new StringBuilder();

    for (int i = 0; i < index; i++) {
      OP op = OP.valueOf(query_op.get(i));
      if (op == null) {
        log.warn("Skipping Invalid Operator: " + query_op.get(i));
        continue;
      }

      if (op == OP.matches || op == OP.doesnt_match) {
        if (regexClause.isEmpty()) {
          log.warn("Skipping Unsupported Regex Operator: " + query_op.get(i));
          continue;
        }
      }

      DetachedCriteria subcriteria = DetachedCriteria.forClass(MetadataValue.class, "mv");
      subcriteria.add(Property.forName("mv.dSpaceObject").eqProperty("item.id"));
      subcriteria.setProjection(Projections.property("mv.dSpaceObject"));

      if (!listFieldList.get(i).isEmpty()) {
        subcriteria.add(Restrictions.in("metadataField", listFieldList.get(i)));
      }

      sb.append(op.name() + " ");
      if (op == OP.equals || op == OP.not_equals) {
        subcriteria.add(Property.forName("mv.value").eq(query_val.get(i)));
        sb.append(query_val.get(i));
      } else if (op == OP.like || op == OP.not_like) {
        subcriteria.add(Property.forName("mv.value").like(query_val.get(i)));
        sb.append(query_val.get(i));
      } else if (op == OP.contains || op == OP.doesnt_contain) {
        subcriteria.add(Property.forName("mv.value").like("%" + query_val.get(i) + "%"));
        sb.append(query_val.get(i));
      } else if (op == OP.matches || op == OP.doesnt_match) {
        subcriteria.add(
            Restrictions.sqlRestriction(regexClause, query_val.get(i), StandardBasicTypes.STRING));
        sb.append(query_val.get(i));
      }

      if (op == OP.exists
          || op == OP.equals
          || op == OP.like
          || op == OP.contains
          || op == OP.matches) {
        criteria.add(Subqueries.exists(subcriteria));
      } else {
        criteria.add(Subqueries.notExists(subcriteria));
      }
    }
    log.debug(String.format("Running custom query with %d filters", index));

    return list(criteria).iterator();
  }
  /**
   * See Interface for functional description.
   *
   * @see UserAccountDaoInterface #retrieveUserAccounts(java.util.Map, int, int, String,
   *     ListSorting)
   */
  @Override
  public List<UserAccount> retrieveUserAccounts(
      final Map<String, Object> criterias,
      final int offset,
      final int maxResults,
      final String orderBy,
      final ListSorting sorting)
      throws SqlDatabaseSystemException {

    final DetachedCriteria detachedCriteria = DetachedCriteria.forClass(UserAccount.class, "user");

    final Map<String, Object> clonedCriterias = new HashMap<String, Object>(criterias);

    // ids
    final Set<String> userAccountIds =
        mergeSets(
            (Set<String>) clonedCriterias.remove(Constants.DC_IDENTIFIER_URI),
            (Set<String>) clonedCriterias.remove(Constants.FILTER_PATH_ID));
    if (userAccountIds != null && !userAccountIds.isEmpty()) {
      detachedCriteria.add(Restrictions.in("id", userAccountIds.toArray()));
    }

    // active flag
    final String active = (String) clonedCriterias.remove(Constants.FILTER_ACTIVE);
    final String active1 = (String) clonedCriterias.remove(Constants.FILTER_PATH_ACTIVE);
    if (active != null) {
      detachedCriteria.add(Restrictions.eq("active", Boolean.valueOf(active)));
    } else if (active1 != null) {
      detachedCriteria.add(Restrictions.eq("active", Boolean.valueOf(active1)));
    }

    for (final Entry<String, Object[]> stringEntry : criteriaMap.entrySet()) {
      if (stringEntry.getKey().equals(Constants.FILTER_ORGANIZATIONAL_UNIT)
          || stringEntry.getKey().equals(Constants.FILTER_PATH_ORGANIZATIONAL_UNIT)) {
        continue;
      }
      final Object criteriaValue = clonedCriterias.remove(stringEntry.getKey());
      if (criteriaValue != null) {
        final Object[] parts = stringEntry.getValue();
        if (parts[0].equals(COMPARE_EQ)) {
          detachedCriteria.add(Restrictions.eq((String) parts[1], criteriaValue));
        } else {
          detachedCriteria.add(Restrictions.like((String) parts[1], criteriaValue));
        }
      }
    }

    // organizational units
    final String organizationalUnit1 =
        (String) clonedCriterias.remove(Constants.FILTER_ORGANIZATIONAL_UNIT);
    final String organizationalUnit2 =
        (String) clonedCriterias.remove(Constants.FILTER_PATH_ORGANIZATIONAL_UNIT);
    final String organizationalUnit =
        organizationalUnit1 != null ? organizationalUnit1 : organizationalUnit2;
    if (organizationalUnit != null) {

      final String ouAttributeName =
          EscidocConfiguration.getInstance()
              .get(EscidocConfiguration.ESCIDOC_CORE_AA_OU_ATTRIBUTE_NAME);

      if (ouAttributeName == null || ouAttributeName.length() == 0) {
        throw new SqlDatabaseSystemException("ou-attribute-name not found in configuration");
      }
      detachedCriteria.add(
          Restrictions.sqlRestriction(
              "this_.id in ("
                  + "select ua.id from aa.user_account ua, "
                  + "aa.user_attribute atts "
                  + "where ua.id = atts.user_id "
                  + "and atts.name = '"
                  + ouAttributeName
                  + "' and atts.value = ?)",
              organizationalUnit,
              Hibernate.STRING));
      // detachedCriteria.add(Restrictions.like("ous", StringUtility
      // .concatenateToString("%", organizationalUnit, "|||%")));
    }

    if (orderBy != null) {
      if (sorting == ListSorting.ASCENDING) {
        detachedCriteria.addOrder(Order.asc(propertiesNamesMap.get(orderBy)));
      } else if (sorting == ListSorting.DESCENDING) {
        detachedCriteria.addOrder(Order.desc(propertiesNamesMap.get(orderBy)));
      }
    }

    if (clonedCriterias.isEmpty()) {
      final List<UserAccount> result;

      try {
        result = getHibernateTemplate().findByCriteria(detachedCriteria, offset, maxResults);
      } catch (final DataAccessException e) {
        throw new SqlDatabaseSystemException(e);
      }
      return result;
    } else {
      // unsupported filter criteria has been found, therefore the result
      // list must be empty.
      return new ArrayList<UserAccount>(0);
    }
  }
  /**
   * This method is for search Presenter
   *
   * @param requestParameters Servlet Request Parameter
   * @return Presenter List
   */
  public ArrayList searchPresenter(HttpServletRequest req) {
    log.log(Level.INFO, "PresenterMaintenance --> search presenter ");
    ArrayList arrPresenter = new ArrayList();

    String presenterName = req.getParameter(NAME_PARAM);
    String category = req.getParameter("presenter_category");
    String month = req.getParameter(MONTH_PARAM);
    String year = req.getParameter(YEAR_PARAM);
    String bu = req.getParameter(BU_PARAM);
    String district = req.getParameter(DISTRICT_PARAM);
    String city = req.getParameter(CITY_PARAM);
    String ssc = req.getParameter(SSC_PARAM);
    String office = req.getParameter("office");
    String branchCode = req.getParameter("branchCode");
    Session session = HibernateFactory.openSession();
    try {
      Criteria crit = session.createCriteria(Presenter.class);
      if (presenterName != null && presenterName.length() > 0)
        crit.add(Restrictions.like("presenterName", presenterName, MatchMode.ANYWHERE));
      if (category != null && Integer.parseInt(category) != 0)
        crit.add(Restrictions.eq("category", Integer.parseInt(category)));
      if (month != null)
        crit.add(
            Restrictions.sqlRestriction(
                "MONTH(START_DATE)=?", Integer.parseInt(month), Hibernate.INTEGER));
      if (year != null)
        crit.add(
            Restrictions.sqlRestriction(
                "YEAR(START_DATE)=?", Integer.parseInt(year), Hibernate.INTEGER));
      if (bu != null && Integer.parseInt(bu) != 0)
        crit.add(Restrictions.eq("buCode", Integer.parseInt(bu)));
      if (district != null && Integer.parseInt(district) != 0)
        crit.add(Restrictions.eq("distCode", Integer.parseInt(district)));

      if (branchCode != null && Integer.parseInt(branchCode) != 0)
        crit.add(Restrictions.eq("branchCode", Integer.parseInt(branchCode)));

      if (city != null && Integer.parseInt(city) != 0)
        crit.add(Restrictions.eq("cityCode", Integer.parseInt(city)));

      if (office != null && Integer.parseInt(office) != 0)
        crit.add(Restrictions.eq("officeCode", Integer.parseInt(office)));

      if (ssc != null && Integer.parseInt(ssc) != 0)
        crit.add(Restrictions.eq("sscCode", Integer.parseInt(ssc)));
      crit.add(Restrictions.eq("status", true));

      List l = crit.list();
      Iterator it = l.iterator();

      while (it.hasNext()) {
        Presenter presenter = (Presenter) it.next();
        arrPresenter.add(presenter);
      }
    } catch (Exception e) {
      log.log(Level.SEVERE, e.getMessage());
      e.printStackTrace();
    }
    try {
      HibernateFactory.close(session);
    } catch (Exception e) {
      log.log(Level.SEVERE, e.getMessage());
      e.printStackTrace();
    }
    return arrPresenter;
  }
  @GlobalDBOpenCloseAndUserPrivilages
  public Map saveMenuAssign(
      Session session,
      HttpServletRequest request,
      HttpServletResponse response,
      String LoggedInRegion,
      String LoggedInUser,
      String usertypes,
      String menucodes) {
    Map resultMap = new HashMap();
    String[] strArray = null;
    String delimiter = "-";
    Transaction transaction = null;
    try {

      Criteria menuCrit = session.createCriteria(Menuprivilages.class);
      menuCrit.add(Restrictions.sqlRestriction("usertype=" + Integer.parseInt(usertypes)));
      List menuList = menuCrit.list();
      if (menuList.size() > 0) {
        for (int i = 0; i < menuList.size(); i++) {
          Menuprivilages menuObj = (Menuprivilages) menuList.get(i);
          transaction = session.beginTransaction();
          menuObj.setAccessright(Boolean.FALSE);
          session.update(menuObj);
          transaction.commit();
        }

        if (!menucodes.equalsIgnoreCase("") && menucodes != null) {
          strArray = menucodes.split(java.util.regex.Pattern.quote(delimiter));
          for (String menuId : strArray) {
            Criteria menuCrit1 = session.createCriteria(Menuprivilages.class);
            menuCrit1.add(Restrictions.sqlRestriction("usertype=" + Integer.parseInt(usertypes)));
            menuCrit1.add(Restrictions.sqlRestriction("menumaster=" + Integer.parseInt(menuId)));
            List menuList1 = menuCrit1.list();
            if (menuList1.size() > 0) {
              transaction = session.beginTransaction();
              Menuprivilages menuObj = (Menuprivilages) menuList1.get(0);
              menuObj.setAccessright(Boolean.TRUE);
              session.update(menuObj);
              transaction.commit();

              this.updateParent(
                  session, menuObj.getMenumaster().getParentcode(), menuObj.getUsertype().getId());

            } else {
              transaction = session.beginTransaction();

              Usertype typeobj = new Usertype();
              typeobj.setId(Integer.parseInt(usertypes));

              Menumaster menuMasterObj = new Menumaster();
              menuMasterObj.setCode(Integer.parseInt(menuId));

              Menuprivilages menuObj = new Menuprivilages();
              menuObj.setId(String.valueOf(getSequenceNumber(session)));
              menuObj.setUsertype(typeobj);
              menuObj.setMenumaster(menuMasterObj);
              menuObj.setAccessright(Boolean.TRUE);
              session.saveOrUpdate(menuObj);
              transaction.commit();

              this.insertParent(session, Integer.parseInt(menuId), Integer.parseInt(usertypes));
            }
          }
        }

      } else {
        Criteria criteria = session.createCriteria(Menumaster.class);
        //                criteria.add(Restrictions.ne("parentcode", 0));
        criteria.addOrder(Order.asc("menuorder"));
        List menumasterlist = criteria.list();
        if (menumasterlist.size() > 0) {
          for (int i = 0; i < menumasterlist.size(); i++) {
            Menumaster menuMasterObj = (Menumaster) menumasterlist.get(i);

            transaction = session.beginTransaction();

            Usertype typeobj = new Usertype();
            typeobj.setId(Integer.parseInt(usertypes));

            Menuprivilages menuObj = new Menuprivilages();
            menuObj.setId(String.valueOf(getSequenceNumber(session)));
            menuObj.setUsertype(typeobj);
            menuObj.setMenumaster(menuMasterObj);
            menuObj.setAccessright(Boolean.FALSE);
            session.save(menuObj);
            transaction.commit();
          }
        }

        if (!menucodes.equalsIgnoreCase("") && menucodes != null) {
          strArray = menucodes.split(java.util.regex.Pattern.quote(delimiter));
          for (String menuId : strArray) {
            Criteria menuCrit1 = session.createCriteria(Menuprivilages.class);
            menuCrit1.add(Restrictions.sqlRestriction("usertype=" + Integer.parseInt(usertypes)));
            menuCrit1.add(Restrictions.sqlRestriction("menumaster=" + Integer.parseInt(menuId)));
            List menuList1 = menuCrit1.list();
            if (menuList1.size() > 0) {
              transaction = session.beginTransaction();
              Menuprivilages menuObj = (Menuprivilages) menuList1.get(0);
              menuObj.setAccessright(Boolean.TRUE);
              session.update(menuObj);
              transaction.commit();

              this.updateParent(
                  session, menuObj.getMenumaster().getParentcode(), menuObj.getUsertype().getId());

            } else {
              transaction = session.beginTransaction();

              Usertype typeobj = new Usertype();
              typeobj.setId(Integer.parseInt(usertypes));

              Menumaster menuMasterObj = new Menumaster();
              menuMasterObj.setCode(Integer.parseInt(menuId));

              Menuprivilages menuObj = new Menuprivilages();
              menuObj.setId(String.valueOf(getSequenceNumber(session)));
              menuObj.setUsertype(typeobj);
              menuObj.setMenumaster(menuMasterObj);
              menuObj.setAccessright(Boolean.TRUE);
              session.save(menuObj);
              transaction.commit();
              this.insertParent(session, Integer.parseInt(menuId), Integer.parseInt(usertypes));
            }
          }
        }
      }

      resultMap.put("success", "Successfully Menus Assigned");
    } catch (Exception e) {
      e.printStackTrace();
      if (transaction != null) {
        transaction.rollback();
      }
      resultMap.put("ERROR", "Menus Assigning Faild");
    }
    return resultMap;
  }
Exemple #23
0
 public EntityFilter sql(String sql) {
   criterias.add(Restrictions.sqlRestriction(sql));
   return this;
 }
  private Criterion parseExpression(Expression expression) {

    ExpressionTypes type = expression.getType();
    String propertyName = expression.getTargetPropertyName();
    Object value = expression.getValue();
    Class<?> clazz;

    if (log.isTraceEnabled()) {
      log.trace(
          String.format(
              "Parsing expression of type '%s' for propety '%s', value=%s",
              type.name(), propertyName, value));
    }

    switch (type) {
      case EQUAL:
        return org.hibernate.criterion.Restrictions.eq(propertyName, value);
      case GREATER:
        return org.hibernate.criterion.Restrictions.gt(propertyName, value);
      case GREATER_OR_EQUAL:
        return org.hibernate.criterion.Restrictions.ge(propertyName, value);
      case LESS:
        return org.hibernate.criterion.Restrictions.lt(propertyName, value);
      case LESS_OR_EQUAL:
        return org.hibernate.criterion.Restrictions.le(propertyName, value);
      case LIKE:
        String sval = (String) value;
        if (sval.contains("%") || sval.contains("_")) {
          return org.hibernate.criterion.Restrictions.ilike(propertyName, sval);
        } else {
          return org.hibernate.criterion.Restrictions.ilike(propertyName, sval, MatchMode.ANYWHERE);
        }
      case LIKE_END:
        return org.hibernate.criterion.Restrictions.ilike(
            propertyName, (String) value, MatchMode.END);
      case LIKE_START:
        return org.hibernate.criterion.Restrictions.ilike(
            propertyName, (String) value, MatchMode.START);
      case LIKE_EXACT:
        return org.hibernate.criterion.Restrictions.ilike(
            propertyName, (String) value, MatchMode.EXACT);
      case BETWEEN:
        return org.hibernate.criterion.Restrictions.between(
            propertyName, ((Object[]) value)[0], ((Object[]) value)[1]);
      case IN:
        clazz = value.getClass();
        if (clazz.isArray()) {
          return org.hibernate.criterion.Restrictions.in(propertyName, (Object[]) value);
        } else if (Collection.class.isAssignableFrom(clazz)) {
          return org.hibernate.criterion.Restrictions.in(propertyName, (Collection<?>) value);
        } else {
          throw new IllegalStateException(
              "Object for 'IN' criteria must be array or collection, but it is "
                  + (clazz == null ? "(null)" : "'" + clazz.getName() + "'"));
        }
      case IS_NULL:
        return org.hibernate.criterion.Restrictions.isNull(propertyName);
      case IS_NOT_NULL:
        return org.hibernate.criterion.Restrictions.isNotNull(propertyName);
      case NOT_EQUAL:
        return org.hibernate.criterion.Restrictions.ne(propertyName, value);
      case EXISTS:
        return Subqueries.exists(subquery((SubqueryExpression) expression));
      case NOT_EXISTS:
        return Subqueries.notExists(subquery((SubqueryExpression) expression));
      case EQUAL_PROPERTY:
        if (!(value instanceof CharSequence)) {
          throw new IllegalStateException(
              "Value for 'EQUAL_PROPERTY' criteria must be CharSequence, but it is "
                  + (value == null ? "(null)" : "'" + value.getClass().getName() + "'"));
        }
        return org.hibernate.criterion.Restrictions.eqProperty(propertyName, value.toString());
      case GREATER_PROPERTY:
        return org.hibernate.criterion.Restrictions.gtProperty(propertyName, value.toString());
      case LESS_PROPERTY:
        return org.hibernate.criterion.Restrictions.ltProperty(propertyName, value.toString());
      case GREATER_EQUAL_PROPERTY:
        return org.hibernate.criterion.Restrictions.geProperty(propertyName, value.toString());
      case LESS_EQUAL_PROPERTY:
        return org.hibernate.criterion.Restrictions.leProperty(propertyName, value.toString());
      case SQL_RESTICTION:
        return org.hibernate.criterion.Restrictions.sqlRestriction(value.toString());
      default:
        throw new IllegalStateException(
            String.format("Unknown query expression '%s'", type.name()));
    }
  }