001/*
002 *  Copyright (c) 2022-2023, Mybatis-Flex (fuhai999@gmail.com).
003 *  <p>
004 *  Licensed under the Apache License, Version 2.0 (the "License");
005 *  you may not use this file except in compliance with the License.
006 *  You may obtain a copy of the License at
007 *  <p>
008 *  http://www.apache.org/licenses/LICENSE-2.0
009 *  <p>
010 *  Unless required by applicable law or agreed to in writing, software
011 *  distributed under the License is distributed on an "AS IS" BASIS,
012 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 *  See the License for the specific language governing permissions and
014 *  limitations under the License.
015 */
016
017package com.mybatisflex.core.exception.locale;
018
019import java.util.Locale;
020import java.util.MissingResourceException;
021import java.util.ResourceBundle;
022
023/**
024 * 异常消息中使用的本地化消息格式的枚举。
025 *
026 * @author 王帅
027 * @author michael
028 *
029 * @since 2023-07-26
030 */
031public enum LocalizedFormats implements Localizable {
032
033    /**
034     * object can not be null
035     */
036    OBJECT_NULL("{0} can not be null."),
037    OBJECT_NULL_OR_BLANK("{0} can not be null or blank."),
038    MAP_NULL_OR_EMPTY("{0} can not be null or empty."),
039    ARRAY_NULL_OR_EMPTY("{0} array can not be null or empty."),
040
041
042    DATASOURCE_TYPE_BLANK("The dataSource type can not be null or blank."),
043    DATASOURCE_TYPE_NOT_FIND("Can not find the dataSource type: {0}"),
044    DATASOURCE_CAN_NOT_INSTANCE("Can not new instance dataSource object by class: {0}"),
045    DATASOURCE_JDBC_URL("Can not get the dataSource jdbcUrl."),
046
047
048    UPDATE_ONLY_SUPPORT_1_TABLE("\"UpdateByQuery\" only support 1 table."),
049    UPDATE_OR_DELETE_NOT_ALLOW("Not allowed \"UPDATE\" or \"DELETE\" a table without where condition."),
050
051
052    ENTITY_VERSION_NULL("The version value of entity \"{0}\" must not be null."),
053
054    KEY_GENERATOR_BLANK("The name of key generator must not be null or blank."),
055    ;
056
057    private final String sourceFormat;
058
059    LocalizedFormats(String sourceFormat) {
060        this.sourceFormat = sourceFormat;
061    }
062
063    @Override
064    public String getSourceString() {
065        return this.sourceFormat;
066    }
067
068    @Override
069    public String getLocalizedString(final Locale locale) {
070        try {
071            // 本地化消息路径
072            String path = LocalizedFormats.class.getName().replace(".", "/");
073            // 获取多语言本地化消息信息文件
074            ResourceBundle bundle = ResourceBundle.getBundle("assets/" + path, locale);
075            // 获取当前语言的消息格式
076            if (bundle.getLocale().getLanguage().equals(locale.getLanguage())) {
077                return bundle.getString(name());
078            }
079        } catch (MissingResourceException mre) {
080            // do nothing here.
081        }
082        // 如果没有该语言的本地化消息,则返回源消息字符串
083        return sourceFormat;
084    }
085
086}