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

com.github.nomou.mybatis.builder.spi.internal.OrderBySource Maven / Gradle / Ivy

package com.github.nomou.mybatis.builder.spi.internal;

import java.beans.Introspector;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * OrderBy.
 */
public class OrderBySource implements Iterable> {
    public static final OrderBySource NONE = new OrderBySource(null);
    private static final String BLOCK_SPLIT = "(?<=Asc|Desc)(?=\\p{Lu})";
    private static final Pattern DIRECTION_SPLIT = Pattern.compile("(.+?)(Asc|Desc)?$");
    private static final String INVALID_ORDER_SYNTAX = "Invalid order syntax for part %s!";
    private static final Set DIRECTION_KEYWORDS = new HashSet(Arrays.asList("Asc", "Desc"));

    /**
     * 通过 LinkedHashMap 来保证顺序.
     */
    private Map orders = new LinkedHashMap();

    public OrderBySource(final String source) {
        if (null != source && !source.isEmpty()) {
            for (final String part : source.split(BLOCK_SPLIT)) {
                final Matcher matcher = DIRECTION_SPLIT.matcher(part);
                if (!matcher.find()) {
                    throw new IllegalArgumentException(String.format(INVALID_ORDER_SYNTAX, part));
                }
                final String property = Introspector.decapitalize(matcher.group(1));
                final String direction = matcher.group(2);

                // No property, but only a direction keyword
                if (DIRECTION_KEYWORDS.contains(property) && null == direction) {
                    throw new IllegalArgumentException(String.format(INVALID_ORDER_SYNTAX, part));
                }
                orders.put(property, null != direction ? direction.toUpperCase(Locale.US) : "ASC");
            }
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Iterator> iterator() {
        return Collections.unmodifiableSet(orders.entrySet()).iterator();
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy