All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.gitee.cn9750wang.webtools.query.Sort Maven / Gradle / Ivy

The newest version!
/*
 *    Copyright 2021 wwy
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package com.gitee.cn9750wang.webtools.query;

import com.gitee.cn9750wang.webtools.error.P21Exception;
import com.gitee.cn9750wang.webtools.error.defines.ParamErr;
import org.apache.commons.lang3.StringUtils;

import java.util.Set;

/**
 * 排序查询对象
 * @author wwy
 */
public class Sort{

    private final String field;

    /**
     * 是否升序,默认升序
     */
    private final boolean asc;

    private static final String ASC = "asc";

    private static final String DESC = "desc";

    /**
     * 排序对象
     * @param str 排序规则
     *            1. xxx      = order by xxx asc
     *            2. xxx~asc  = order by xxx asc
     *            3. xxx~desc = order by xxx desc
     */
    public Sort(String str){
        final var spiltIndex = StringUtils.indexOf(str,'~');
        if(spiltIndex == StringUtils.INDEX_NOT_FOUND){
            this.field = str.replaceAll("[A-Z]", "_$0").toLowerCase();
            asc = true;
            return;
        }
        field = StringUtils.substring(str,0,spiltIndex)
                           .replaceAll("[A-Z]", "_$0").toLowerCase();
        final var sortRole = StringUtils.substring(str,spiltIndex + 1);
        if(ASC.equalsIgnoreCase(sortRole)){
            asc = true;
        }else if(DESC.equalsIgnoreCase(sortRole)){
            asc = false;
        }else {
            throw new P21Exception("排序规则错误");
        }
    }


    /**
     * 检查前端传入的排序字段是否能够进行排序
     * @param fields 可供排序用的字段
     * @return true可以排序
     */
    public boolean isSortable(Set fields){
        return fields != null && fields.contains(field);
    }

    /**
     * 检查Sort对象中的字段是否可以排序,如果不可排序将抛出异常
     * @param fields 可排序字段
     */
    public void check(Set fields){
        ParamErr.UN_SORT.isTrue(isSortable(fields),field);
    }

    public String getField() {
        return field;
    }

    public boolean isAsc() {
        return asc;
    }

    @Override
    public String toString() {
        return field + " " + (asc ? ASC : DESC);
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy