From 4af72ed177aa93cc6cc04738213dbe5f4de089a4 Mon Sep 17 00:00:00 2001 From: wangjian Date: Tue, 8 Aug 2023 11:43:20 +0800 Subject: [PATCH] =?UTF-8?q?Signed-off-by:=E7=8E=8B=E5=89=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: wangjian --- frameworks/i18n/src/data_resource.cpp | 6 +- frameworks/i18n/src/date_time_data.cpp | 2 +- frameworks/i18n/src/plural_format_impl.cpp | 6 +- .../java/ohos/global/i18n/DataFetcher.java | 64 +++++++------ .../main/java/ohos/global/i18n/Fetcher.java | 92 ++++++++++++------- .../java/ohos/global/i18n/FileConfig.java | 7 ++ .../java/ohos/global/i18n/LocaleConfig.java | 11 ++- .../java/ohos/global/i18n/LocaleList.java | 5 + .../java/ohos/global/i18n/LocaleMaskItem.java | 7 +- .../java/ohos/global/i18n/PluralFetcher.java | 25 ++--- .../global/i18n/ResourceConfiguration.java | 2 + .../java/ohos/global/i18n/StringPool.java | 12 ++- .../src/main/java/ohos/global/i18n/Utils.java | 35 +++---- 13 files changed, 172 insertions(+), 102 deletions(-) diff --git a/frameworks/i18n/src/data_resource.cpp b/frameworks/i18n/src/data_resource.cpp index 4459a93..4f7aceb 100644 --- a/frameworks/i18n/src/data_resource.cpp +++ b/frameworks/i18n/src/data_resource.cpp @@ -23,9 +23,9 @@ using namespace OHOS::I18N; using namespace std; #ifdef I18N_PRODUCT -static const char *gDataResourcePath = "system/i18n/i18n.dat"; +static const char *g_DataResourcePath = "system/i18n/i18n.dat"; #else -static const char *gDataResourcePath = "/storage/data/i18n.dat"; +static const char *g_DataResourcePath = "/storage/data/i18n.dat"; #endif DataResource::DataResource(const LocaleInfo *localeInfo) @@ -145,7 +145,7 @@ char *DataResource::BinarySearchString(uint32_t *indexArray, uint32_t length, ui bool DataResource::Init(void) { - int32_t infile = open(gDataResourcePath, O_RDONLY); + int32_t infile = open(g_DataResourcePath, O_RDONLY); if (infile < 0) { return false; } diff --git a/frameworks/i18n/src/date_time_data.cpp b/frameworks/i18n/src/date_time_data.cpp index 3346b6e..0adf86a 100644 --- a/frameworks/i18n/src/date_time_data.cpp +++ b/frameworks/i18n/src/date_time_data.cpp @@ -31,7 +31,7 @@ DateTimeData::DateTimeData(const char *amPmMarkers, const char *configs, const i } // size must >= 2, The first 2 element of configs need to be extracted, the first element // is the time separator and the second is the default hour. - if (configs && size >= 2) { + if (configs && size >= 2) { // 2 is the size of configs need to be extracted timeSeparator = configs[0]; defaultHour = configs[1]; } diff --git a/frameworks/i18n/src/plural_format_impl.cpp b/frameworks/i18n/src/plural_format_impl.cpp index fef436e..90c61ee 100644 --- a/frameworks/i18n/src/plural_format_impl.cpp +++ b/frameworks/i18n/src/plural_format_impl.cpp @@ -145,9 +145,9 @@ void PluralFormatImpl::ComputeDecimalInfo(double number, int integerNumber, int temp = round(temp); } if (temp - ((int)temp) < EPS) { - while (i > 1 && (int) temp % 10 == 0) { + while (i > 1 && (int) temp % 10 == 0) { // 10 means decimal i--; - temp /= 10; + temp /= 10; // 10 means decimal } // 10 is base fractionNumber = (int)(temp - integerNumber * pow(10, i)); @@ -378,7 +378,7 @@ int PluralFormatImpl::ParseNumber(const std::string &rule, const int ruleSize, i // Parse number in the formula. while ((index < ruleSize) && (rule[index] != ' ') && (rule[index] != TO) && (rule[index] != COMMA)) { - num *= 10; // Calculate decimal value of the number. + num *= 10; // 10 means decimal. Calculate decimal value of the number. num += rule[index] - '0'; index++; } diff --git a/tools/i18n-dat-tool/src/main/java/ohos/global/i18n/DataFetcher.java b/tools/i18n-dat-tool/src/main/java/ohos/global/i18n/DataFetcher.java index ea6ded9..10f9ca6 100644 --- a/tools/i18n-dat-tool/src/main/java/ohos/global/i18n/DataFetcher.java +++ b/tools/i18n-dat-tool/src/main/java/ohos/global/i18n/DataFetcher.java @@ -24,8 +24,8 @@ import java.io.BufferedReader; import java.io.FileOutputStream; import java.net.URISyntaxException; import java.nio.charset.StandardCharsets; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; +import java.util.concurrent.ArrayBlockingQueue; +import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReentrantLock; import java.util.ArrayList; @@ -45,6 +45,8 @@ import net.sf.json.JSONObject; /** * This class is used to generate i18n.dat file + * + * @since 2022-8-22 */ public class DataFetcher { private static final ReentrantLock LOCK = new ReentrantLock(); @@ -68,11 +70,17 @@ public class DataFetcher { private static final Pattern RE_LANGUAGE = Pattern.compile("^([a-z]{2,3})-\\*$"); private static final int MAX_TIME_TO_WAIT = 10; private static final String SEP = File.separator; + private static final int CORE_POOL_SIZE = 1000; + private static final int MAX_POOL_SIZE = 1000; + private static final int QUEUE_CAPACITY = 2000; + private static final Long KEEP_ALIVE_TIME = 1L; static { addFetchers(); } + private DataFetcher() {} + /** * * Add all required locales from locale.txt and fetch its related data. @@ -116,7 +124,6 @@ public class DataFetcher { private static int processWildcard(String line, ULocale[] availableLocales, int count) { String tag = line.trim(); int tempCount = count; - Matcher matcher = RE_LANGUAGE.matcher(line); if ("*".equals(line)) { // special treatment to wildcard xx-* for (ULocale loc : availableLocales) { String finalLanguageTag = loc.toLanguageTag(); @@ -129,6 +136,7 @@ public class DataFetcher { } return tempCount; } + Matcher matcher = RE_LANGUAGE.matcher(line); if (matcher.matches()) { // special treatment to wildcard language-* String baseName = matcher.group(1); for (ULocale loc : availableLocales) { @@ -148,7 +156,26 @@ public class DataFetcher { return sStatus == 0; } - private DataFetcher() {} + private static int countData(Fetcher currentFetcher, int count, Fetcher fallbackFetcher, ArrayList temp) { + String fallbackData = null; + for (int i = 0; i < Fetcher.getResourceCount(); i++) { + String targetMetaData = Fetcher.getInt2Str().get(i); + String myData = currentFetcher.datas.get(i); + if (fallbackFetcher != null) { + fallbackData = fallbackFetcher.datas.get(i); + } else { + fallbackData = null; + } + if (!myData.equals(fallbackData)) { + temp.add(new LocaleConfig(targetMetaData, i, ID_MAP.get(myData))); + ++count; + currentFetcher.reservedAdd(1); + } else { + currentFetcher.reservedAdd(0); + } + } + return count; + } /** * If a locale's data equals to its fallback's data, this locale is excluded @@ -160,7 +187,6 @@ public class DataFetcher { */ private static int buildLocaleConfigs() { Fetcher fallbackFetcher = null; - String fallbackData = null; int count = 0; for (Map.Entry entry : LOCALES.entrySet()) { String languageTag = entry.getKey(); @@ -177,24 +203,9 @@ public class DataFetcher { fallbackFetcher = FETCHERS.get(LOCALES.get(fallbackLanguageTag)); } if (currentFetcher.equals(fallbackFetcher)) { - currentFetcher.included = false; + currentFetcher.setIncluded(false); } else { - for (int i = 0; i < Fetcher.getResourceCount(); i++) { - String targetMetaData = Fetcher.getInt2Str().get(i); - String myData = currentFetcher.datas.get(i); - if (fallbackFetcher != null) { - fallbackData = fallbackFetcher.datas.get(i); - } else { - fallbackData = null; - } - if (!myData.equals(fallbackData)) { - temp.add(new LocaleConfig(targetMetaData, i, ID_MAP.get(myData))); - ++count; - currentFetcher.reservedAdd(1); - } else { - currentFetcher.reservedAdd(0); - } - } + count = countData(currentFetcher, count, fallbackFetcher, temp); } } return count; @@ -270,7 +281,7 @@ public class DataFetcher { for (Fetcher fetcher : FETCHERS) { String language = fetcher.languageTag; String data = fetcher.datas.get(index); - if (data.length() == 0 || !fetcher.included || fetcher.reservedGet(index) == 0) { + if (data.length() == 0 || !fetcher.getIncluded() || fetcher.reservedGet(index) == 0) { continue; } String[] values = data.split("_", -1); @@ -348,11 +359,12 @@ public class DataFetcher { * * @param args Main function's argument */ - public static void main(String args[]) { + public static void main(String[] args) { if (!Fetcher.isFetcherStatusOk() || !checkStatus()) { return; } - ExecutorService exec = Executors.newCachedThreadPool(); + ThreadPoolExecutor exec = new ThreadPoolExecutor(CORE_POOL_SIZE, MAX_POOL_SIZE, + KEEP_ALIVE_TIME, TimeUnit.SECONDS, new ArrayBlockingQueue<>(QUEUE_CAPACITY)); for (Fetcher fe : FETCHERS) { exec.execute(fe); } @@ -364,7 +376,7 @@ public class DataFetcher { } buildLocaleConfigs(); // every metaData needs 6 bytes for (Fetcher fetcher : FETCHERS) { - if (!fetcher.included) { + if (!fetcher.getIncluded()) { LOCALES.remove(fetcher.languageTag); } } diff --git a/tools/i18n-dat-tool/src/main/java/ohos/global/i18n/Fetcher.java b/tools/i18n-dat-tool/src/main/java/ohos/global/i18n/Fetcher.java index d6f1719..6da80af 100644 --- a/tools/i18n-dat-tool/src/main/java/ohos/global/i18n/Fetcher.java +++ b/tools/i18n-dat-tool/src/main/java/ohos/global/i18n/Fetcher.java @@ -40,7 +40,9 @@ import ohos.global.i18n.ResourceConfiguration.ConfigItem; import ohos.global.i18n.ResourceConfiguration.Element; /** - * Fetcher is used to fetche a locale's specified data + * Fetcher is used to fetche a locale's specified data. + * + * @since 2022-8-22 */ public class Fetcher implements Runnable, Comparable { /** configuration extracted from resourec_items.json */ @@ -57,18 +59,22 @@ public class Fetcher implements Runnable, Comparable { resourceCount = configItems.size(); } - /** Used to store data related to a locale */ - public ArrayList datas = new ArrayList<>(); - - /** All non-repeated strings will be put into idMap */ - public Map idMap; + /** + * Used to store data related to a locale. + */ + public final ArrayList datas = new ArrayList<>(); - /** Indicate whether this Fetcher is included in the final generation process of i18n.dat file */ - public boolean included = true; + /** + * All non-repeated strings will be put into idMap. + */ + public final Map idMap; - /** LanguageTag related to the locale */ - public String languageTag; + /** + * LanguageTag related to the locale. + */ + public final String languageTag; + private boolean included = true; // Indicate whether this Fetcher is included in the final generation process of i18n.dat file. private String lan; // language private ReentrantLock lock; // Lock used to synchronize dump operation private ULocale locale; @@ -78,6 +84,26 @@ public class Fetcher implements Runnable, Comparable { private String defaultHourString; private ArrayList reserved = new ArrayList<>(); + /** + * Constructor of class Fetcher. + */ + public Fetcher(String tag, ReentrantLock lock, Map idMap) { + if (!Utils.isValidLanguageTag(tag)) { + LOG.log(Level.SEVERE, String.format("wrong languageTag %s", tag)); + status = 1; + } + this.languageTag = tag; + Objects.requireNonNull(lock); + this.lock = lock; + Objects.requireNonNull(idMap); + this.idMap = idMap; + this.lan = this.languageTag.split("-")[0]; + this.locale = ULocale.forLanguageTag(this.languageTag); + formatSymbols = DateFormatSymbols.getInstance(locale); + patternGenerator = DateTimePatternGenerator.getInstance(locale); + defaultHourString = defaultHour(); + } + /** * show whether resouce_items is loaded successfully * @@ -114,23 +140,6 @@ public class Fetcher implements Runnable, Comparable { return str2Int; } - public Fetcher(String tag, ReentrantLock lock, Map idMap) { - if (!Utils.isValidLanguageTag(tag)) { - LOG.log(Level.SEVERE, String.format("wrong languageTag %s", tag)); - status = 1; - } - this.languageTag = tag; - Objects.requireNonNull(lock); - this.lock = lock; - Objects.requireNonNull(idMap); - this.idMap = idMap; - this.lan = this.languageTag.split("-")[0]; - this.locale = ULocale.forLanguageTag(this.languageTag); - formatSymbols = DateFormatSymbols.getInstance(locale); - patternGenerator = DateTimePatternGenerator.getInstance(locale); - defaultHourString = defaultHour(); - } - /** * Check the status of the fetcher, normally a wrong language tag * can make the status wrong. @@ -157,13 +166,27 @@ public class Fetcher implements Runnable, Comparable { method = Fetcher.class.getDeclaredMethod(methodString, ConfigItem.class); method.setAccessible(true); method.invoke(this, item); - } catch(IllegalAccessException | NoSuchMethodException | InvocationTargetException e) { + } catch (IllegalAccessException | NoSuchMethodException | InvocationTargetException e) { LOG.severe("get data failed for index " + current); } ++current; } } + /** + * Get included. + */ + public boolean getIncluded() { + return included; + } + + /** + * Set included. + */ + public void setIncluded(boolean val) { + included = val; + } + /** * Dump all datas in this locale to idMap */ @@ -350,11 +373,11 @@ public class Fetcher implements Runnable, Comparable { Field patternField = DateFormat.class.getField(skeleton); int patternIndex = patternField.getInt(null); formatter = DateFormat.getDateInstance(patternIndex, locale); - } catch (NoSuchFieldException | IllegalArgumentException | IllegalAccessException e ) { + } catch (NoSuchFieldException | IllegalArgumentException | IllegalAccessException e) { LOG.log(Level.SEVERE, "cannot get field " + skeleton); } if (formatter instanceof SimpleDateFormat) { - return ((SimpleDateFormat)formatter).toPattern(); + return ((SimpleDateFormat) formatter).toPattern(); } else { LOG.log(Level.SEVERE, "wrong type in getFMSPattern"); return ""; @@ -404,13 +427,13 @@ public class Fetcher implements Runnable, Comparable { // 6. get number format data @SuppressWarnings("Deprecation") private void getNumberFormat(ConfigItem config) { + StringBuilder sb = new StringBuilder(); String pattern = NumberFormat.getPatternForStyle(locale, NumberFormat.NUMBERSTYLE); String percentPattern = NumberFormat.getPatternForStyle(locale, NumberFormat.PERCENTSTYLE); DecimalFormatSymbols decimalFormatSymbols = new DecimalFormatSymbols(locale); - String percent = decimalFormatSymbols.getPercentString(); - String groupingSeparator = decimalFormatSymbols.getGroupingSeparatorString(); String decimalSeparator = decimalFormatSymbols.getDecimalSeparatorString(); - StringBuilder sb = new StringBuilder(); + String groupingSeparator = decimalFormatSymbols.getGroupingSeparatorString(); + String percent = decimalFormatSymbols.getPercentString(); sb.append(pattern); sb.append(FileConfig.SEP); sb.append(percentPattern); @@ -527,7 +550,8 @@ public class Fetcher implements Runnable, Comparable { } } - public @Override int compareTo(Fetcher other) { + @Override + public int compareTo(Fetcher other) { if (languageTag == null && other.languageTag == null) { return 0; } diff --git a/tools/i18n-dat-tool/src/main/java/ohos/global/i18n/FileConfig.java b/tools/i18n-dat-tool/src/main/java/ohos/global/i18n/FileConfig.java index d8c26ab..02290d7 100644 --- a/tools/i18n-dat-tool/src/main/java/ohos/global/i18n/FileConfig.java +++ b/tools/i18n-dat-tool/src/main/java/ohos/global/i18n/FileConfig.java @@ -17,6 +17,8 @@ package ohos.global.i18n; /** * This class encapsulate some configurations + * + * @since 2022-8-22 */ public class FileConfig { /** @@ -28,22 +30,27 @@ public class FileConfig { * Version number */ public static final int FILE_VERSION = 1; + /** * Dat file's header size is 16 bytes */ public static final int HEADER_SIZE = 16; + /** * Every locale need 8 bytes */ public static final int LOCALE_MASK_ITEM_SIZE = 8; + /** * Locales mask is a 4-byte-length unsigned integer */ public static final int LOCALE_MASK_SIZE = 4; + /** * Separator used to separate numbers */ public static final String NUMBER_SEP = ";"; + /** * Separator used to separate (except numbers) */ diff --git a/tools/i18n-dat-tool/src/main/java/ohos/global/i18n/LocaleConfig.java b/tools/i18n-dat-tool/src/main/java/ohos/global/i18n/LocaleConfig.java index e715645..dd2cdc4 100644 --- a/tools/i18n-dat-tool/src/main/java/ohos/global/i18n/LocaleConfig.java +++ b/tools/i18n-dat-tool/src/main/java/ohos/global/i18n/LocaleConfig.java @@ -17,17 +17,22 @@ package ohos.global.i18n; /** * Represents a meta data config in dat file + * + * @since 2022-8-22 */ public class LocaleConfig { /** Meata data's name for example calendar/gregorian/monthNames/format/abbreviated */ - public String name; + public final String name; /** Meta data's index in str2Int */ - public int nameId; + public final int nameId; /** Meta data's index in sIdMap */ - public int stringId; + public final int stringId; + /** + * Constructor of class LocaleConfig + */ public LocaleConfig(String str, int nameId, int stringId) { this.name = str; this.nameId = nameId; diff --git a/tools/i18n-dat-tool/src/main/java/ohos/global/i18n/LocaleList.java b/tools/i18n-dat-tool/src/main/java/ohos/global/i18n/LocaleList.java index 01c565d..62f9c1d 100644 --- a/tools/i18n-dat-tool/src/main/java/ohos/global/i18n/LocaleList.java +++ b/tools/i18n-dat-tool/src/main/java/ohos/global/i18n/LocaleList.java @@ -23,6 +23,8 @@ import java.util.Map; /** * Represents a locale in dat file + * + * @since 2022-8-22 */ public class LocaleList { private ArrayList list = new ArrayList<>(70); @@ -30,6 +32,9 @@ public class LocaleList { private int size; private int startOffset; + /** + * Constructor of class LocaleList. + */ public LocaleList(int startOffset, HashMap locales, Map> localeConfigs, StringPool stringPool) { this.startOffset = startOffset; diff --git a/tools/i18n-dat-tool/src/main/java/ohos/global/i18n/LocaleMaskItem.java b/tools/i18n-dat-tool/src/main/java/ohos/global/i18n/LocaleMaskItem.java index 82fe29b..5af63d4 100644 --- a/tools/i18n-dat-tool/src/main/java/ohos/global/i18n/LocaleMaskItem.java +++ b/tools/i18n-dat-tool/src/main/java/ohos/global/i18n/LocaleMaskItem.java @@ -25,6 +25,8 @@ import com.ibm.icu.util.ULocale; /** * Represent the mask value of a locale + * + * @since 2022-8-22 */ public class LocaleMaskItem implements Comparable { private static final Logger logger = Logger.getLogger("LocaleMaskItem"); @@ -35,13 +37,16 @@ public class LocaleMaskItem implements Comparable { private int offset = -1; private ArrayList configs; + /** + * Constructor of class LocaleMaskItem. + */ public LocaleMaskItem(String languageTag, ArrayList configs) { this.languageTag = languageTag; this.configs = configs; configs.sort(new Comparator() { @Override public int compare(LocaleConfig first, LocaleConfig second) { - if (first.nameId == second.nameId) { + if (first.nameId == second.nameId) { return 0; } else if (first.nameId < second.nameId) { return -1; diff --git a/tools/i18n-dat-tool/src/main/java/ohos/global/i18n/PluralFetcher.java b/tools/i18n-dat-tool/src/main/java/ohos/global/i18n/PluralFetcher.java index 8460be5..8fe46bb 100644 --- a/tools/i18n-dat-tool/src/main/java/ohos/global/i18n/PluralFetcher.java +++ b/tools/i18n-dat-tool/src/main/java/ohos/global/i18n/PluralFetcher.java @@ -28,28 +28,31 @@ import java.util.logging.Level; /** * This class is used to extract plural data related to a locale + * + * @since 2022-8-22 */ public class PluralFetcher { - private static PluralFetcher PLURAL = new PluralFetcher(); + private static PluralFetcher plural = new PluralFetcher(); private static final Logger logger = Logger.getLogger("PluralFetcher"); - private HashMap map; - private HashMap decimalMap; static { - PLURAL.init(); + plural.init(); } + private HashMap map; + private HashMap decimalMap; + + private PluralFetcher() {} + /** * Return the singleton instance * - * @return PLURAL + * @return plural */ public static PluralFetcher getInstance() { - return PLURAL; + return plural; } - private PluralFetcher() {} - private void init() { try (BufferedReader fin = new BufferedReader(new InputStreamReader(new FileInputStream( new File(MeasureFormatPatternFetcher.class.getResource("/resource/plural.txt").toURI())), @@ -111,7 +114,8 @@ public class PluralFetcher { String[] splits = trimedLine.split(" ", 2); // Split into 2 parts if (splits.length != 2) { logger.log(Level.SEVERE, "Init error"); - return null; + String[] emptyArray = new String[0]; + return emptyArray; } String languageTag = splits[0]; if (!languageTag.contains("-")) { @@ -123,8 +127,7 @@ public class PluralFetcher { String[] resources = splits[1].split(", "); StringBuilder sb = new StringBuilder(); for (int i = 0; i < resources.length; ++i) { - // skip "" - if (resources[i].length() > 2) { + if (resources[i].length() > 2) { // 2 means skip "" int length = resources[i].length(); sb.append(resources[i].substring(1, length - 1)); } diff --git a/tools/i18n-dat-tool/src/main/java/ohos/global/i18n/ResourceConfiguration.java b/tools/i18n-dat-tool/src/main/java/ohos/global/i18n/ResourceConfiguration.java index 7237eb2..1a0ad1f 100644 --- a/tools/i18n-dat-tool/src/main/java/ohos/global/i18n/ResourceConfiguration.java +++ b/tools/i18n-dat-tool/src/main/java/ohos/global/i18n/ResourceConfiguration.java @@ -27,6 +27,8 @@ import java.util.ArrayList; /** * Resource configuration defined in the reource_items.json + * + * @since 2022-8-22 */ public class ResourceConfiguration { private ResourceConfiguration() {} diff --git a/tools/i18n-dat-tool/src/main/java/ohos/global/i18n/StringPool.java b/tools/i18n-dat-tool/src/main/java/ohos/global/i18n/StringPool.java index 69e7bc1..1438c58 100644 --- a/tools/i18n-dat-tool/src/main/java/ohos/global/i18n/StringPool.java +++ b/tools/i18n-dat-tool/src/main/java/ohos/global/i18n/StringPool.java @@ -28,17 +28,22 @@ import com.ibm.icu.util.ULocale; /** * Represents the global string pool in i18n.dat file + * + * @since 2022-8-22 */ public class StringPool { private static final String ARABIC_PERCENT = new DecimalFormatSymbols(new ULocale("ar")).getPercentString(); private static final Logger logger = Logger.getLogger("StringPool"); + private HashMap lengthMap = new HashMap<>(); private int size; private HashMap offsetMap; private HashMap int2StrMap = new HashMap<>(); + /** + * Constructor of class StringPool. + */ public StringPool(HashMap hashMap, int offset) { - int current = 0; size = hashMap.size(); for (Map.Entry next : hashMap.entrySet()) { this.int2StrMap.put(next.getValue(), next.getKey()); @@ -54,6 +59,7 @@ public class StringPool { } offsetMap = new HashMap<>(); int currentIndex = 0; + int current = 0; while (true) { if (currentIndex < this.size) { int stringLength = lengthMap.get(currentIndex); @@ -71,10 +77,10 @@ public class StringPool { */ public static class StringItem { /** Length of a string */ - public int length; + public final int length; /** Offset from the begging of the string pool */ - public int offset; + public final int offset; public StringItem(int length, int offset) { this.offset = length; diff --git a/tools/i18n-dat-tool/src/main/java/ohos/global/i18n/Utils.java b/tools/i18n-dat-tool/src/main/java/ohos/global/i18n/Utils.java index 0a5cf79..d01c09a 100644 --- a/tools/i18n-dat-tool/src/main/java/ohos/global/i18n/Utils.java +++ b/tools/i18n-dat-tool/src/main/java/ohos/global/i18n/Utils.java @@ -37,10 +37,10 @@ import ohos.global.i18n.ResourceConfiguration.Element; /** * utils class. + * + * @since 2022-8-22 */ public class Utils { - private Utils() {} - private static final String AVAILABLE_LINE = "enum AvailableDateTimeFormatPattern {"; private static final String AVAILABLE_END_LINE = "};"; private static final int TYPE_SHIFT = 16; @@ -48,6 +48,8 @@ public class Utils { private static final String I18N_MACROS_BEGIN = "// this file should only be included by date_time_format_impl.cpp"; private static final int MAX_CASE_NUMBER = 14; + private Utils() {} + /** * Get a locale's fallback, locale is specified with languageTag * @@ -136,7 +138,7 @@ public class Utils { return false; } for (int i = 0; i < length; ++i) { - if (i == 0 ) { + if (i == 0) { if (!Character.isUpperCase(script.charAt(0))) { return false; } @@ -171,7 +173,7 @@ public class Utils { * @param hashCode reserved for future use * @param localesCount valid locales in total * @param metaCount all metaData in total - * @throws IOException + * @throws IOException throw IOException if write error happen */ public static void writeHeader(DataOutputStream out, int hashCode, int localesCount, int metaCount) throws IOException { @@ -182,7 +184,7 @@ public class Utils { out.writeChar(0); // reserved out.writeChar(FileConfig.HEADER_SIZE + 8 * localesCount); out.writeChar(localesCount); - out.writeChar(FileConfig.HEADER_SIZE + 8 * localesCount + metaCount * 6); + out.writeChar(FileConfig.HEADER_SIZE + 8 * localesCount + metaCount * 6); out.flush(); } @@ -195,7 +197,7 @@ public class Utils { * @throws UnsupportedEncodingException if getBytes function failed */ public static String getMask(ULocale locale, long[] maskOut) throws UnsupportedEncodingException { - long mask = 0; + long mask = 0L; byte[] langs; // Deal with "fil" and "mai" these 3-leters language if ("fil".equals(locale.getLanguage())) { @@ -205,7 +207,7 @@ public class Utils { } else { langs = locale.getLanguage().getBytes("utf-8"); } - mask = mask | ((long)(langs[0] - 48)) << 25 | ((long)(langs[1] - 48)) << 18; + mask = mask | ((long) (langs[0] - 48)) << 25 | ((long) (langs[1] - 48)) << 18; int temp = 0; if ("Latn".equals(locale.getScript())) { temp = 1; @@ -222,14 +224,13 @@ public class Utils { } else { temp = "Guru".equals(locale.getScript()) ? 7 : 0; } - mask = mask | ((long)temp << 14); + mask = mask | ((long) temp << 14); if (locale.getCountry() != null && locale.getCountry().length() == 2) { byte[] ret = locale.getCountry().getBytes("utf-8"); - mask = mask | ((long) (ret[0] - 48) << 7) | ((long)(ret[1] - 48)); + mask = mask | ((long) (ret[0] - 48) << 7) | ((long) (ret[1] - 48)); } maskOut[0] = mask; - String ret = "0x" + Long.toHexString(mask); - return ret; + return "0x" + Long.toHexString(mask); } /** @@ -266,7 +267,6 @@ public class Utils { } private static String generateAvailableDateTimeFormatPattern(ArrayList configItems) { - StringBuilder sb = new StringBuilder(); ArrayList adjust = new ArrayList<>(); for (ConfigItem item : configItems) { if ("true".equals(item.pub) && item.elements != null) { @@ -287,6 +287,7 @@ public class Utils { } } }); + StringBuilder sb = new StringBuilder(); for (int i = 0; i < adjust.size(); ++i) { sb.append("\t"); sb.append(adjust.get(i).getAvailableFormat()); @@ -299,7 +300,6 @@ public class Utils { } private static String generateI18nPatternMacros(ArrayList configItems) { - StringBuilder sb = new StringBuilder(); ArrayList adjust = new ArrayList<>(); for (ConfigItem item : configItems) { if (item.elements != null) { @@ -319,6 +319,7 @@ public class Utils { } }); int current = 0; + StringBuilder sb = new StringBuilder(); for (ConfigItem item : adjust) { int type = current++; int innerIndex = 0; @@ -343,8 +344,8 @@ public class Utils { * @param items ConfigItems extracted from resource_items.json */ public static void generateI18nPatternFile(File src, File dst, ArrayList items) { - try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(src))); - BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(dst)))) { + try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(src), "utf-8")); + BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(dst), "utf-8"))) { String line = null; boolean found = false; while ((line = reader.readLine()) != null) { @@ -473,7 +474,7 @@ public class Utils { } } for (int i = 0; i < adjust.size(); ++i) { - if ( i != adjust.size() - 1) { + if (i != adjust.size() - 1) { sb.append(" case " + adjust.get(i).type + ": {" + System.lineSeparator()); } else { sb.append(" default: {" + System.lineSeparator()); @@ -494,7 +495,7 @@ public class Utils { if (configItems.get(i).type == null) { continue; } - if ( i == 0) { + if (i == 0) { sb.append(" " + configItems.get(i).type + " = PATTERN_TYPE_BEGIN," + System.lineSeparator()); } else { sb.append(" " + configItems.get(i).type + "," + System.lineSeparator()); -- Gitee