/**
   * Generates the HQL Sort By Clause to append to the query being executed. If no sort options is
   * set on the sortBy parameter the result is ordered by the first shown grid's column.
   *
   * @param sortBy String of grid's field names concatenated by
   *     JsonConstants.IN_PARAMETER_SEPARATOR.
   * @param sel the selector that it is being displayed.
   * @return a String with the HQL Sort By clause.
   */
  private String getSortClause(String sortBy, Selector sel) {
    StringBuffer sortByClause = new StringBuffer();
    boolean sortByDesc = false;
    if (sortBy != null && sortBy.startsWith("-")) {
      sortByDesc = true;
    }
    // If grid is manually filtered sortBy is not empty
    if (StringUtils.isNotEmpty(sortBy)) {
      if (sortBy.contains(JsonConstants.IN_PARAMETER_SEPARATOR)) {
        final String[] fieldNames = sortBy.split(JsonConstants.IN_PARAMETER_SEPARATOR);
        for (String fieldName : fieldNames) {
          if (sortByDesc) {
            fieldName = fieldName.substring(1, fieldName.length());
          }
          int fieldSortIndex = getFieldSortIndex(fieldName, sel);
          if (fieldSortIndex > 0) {
            if (sortByClause.length() > 0) {
              sortByClause.append(", ");
            }
            if (sortByDesc) {
              sortByClause.append(fieldSortIndex + " desc");
            } else {
              sortByClause.append(fieldSortIndex);
            }
          }
        }
      } else {
        String fieldName = null;
        if (sortByDesc) {
          fieldName = sortBy.substring(1, sortBy.length());
        } else {
          fieldName = sortBy;
        }
        int fieldSortIndex = getFieldSortIndex(fieldName, sel);
        if (fieldSortIndex > 0) {
          if (sortByDesc) {
            sortByClause.append(fieldSortIndex + " desc");
          } else {
            sortByClause.append(fieldSortIndex);
          }
        }
      }
    }

    // If sortByClause is empty set default sort options.
    if (sortByClause.length() == 0) {
      OBCriteria<SelectorField> selFieldsCrit =
          OBDao.getFilteredCriteria(
              SelectorField.class,
              Restrictions.eq(SelectorField.PROPERTY_OBUISELSELECTOR, sel),
              Restrictions.eq(SelectorField.PROPERTY_SHOWINGRID, true));
      selFieldsCrit.addOrderBy(SelectorField.PROPERTY_SORTNO, true);
      for (SelectorField selField : selFieldsCrit.list()) {
        int fieldSortIndex = getFieldSortIndex(selField.getDisplayColumnAlias(), sel);
        if (fieldSortIndex > 0) {
          sortByClause.append(fieldSortIndex + ", ");
        }
      }
      // Delete last 2 characters: ", "
      if (sortByClause.length() > 0) {
        sortByClause.delete(sortByClause.length() - 2, sortByClause.length() - 1);
      }
    }
    String result = "";
    if (sortByClause.length() > 0) {
      result = "\n ORDER BY " + sortByClause.toString();
    }

    return result;
  }