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

uk.autores.handling.LocalePatterns Maven / Gradle / Ivy

There is a newer version: 11.0.35-beta
Show newest version
// Copyright 2023 https://github.com/autores-uk/autores/blob/main/LICENSE.txt
// SPDX-License-Identifier: Apache-2.0
package uk.autores.handling;

import java.util.*;
import java.util.function.Function;

import static java.util.Collections.unmodifiableSortedMap;

final class LocalePatterns {

    private SortedMap relationships;

    private Map relationships() {
        if (relationships == null) {
            ResourceBundle.Control ctrl = ResourceBundle.Control.getControl(ResourceBundle.Control.FORMAT_PROPERTIES);
            relationships = new TreeMap<>();
            for (Locale l : Locale.getAvailableLocales()) {
                if (l.getLanguage().isEmpty()) {
                    continue;
                }
                String pattern = ctrl.toBundleName("", l);
                String[] candidates = candidates(ctrl, l, pattern);
                relationships.put(pattern, candidates);
            }
            relationships = unmodifiableSortedMap(relationships);
        }
        return relationships;
    }

    Set patterns() {
        return relationships().keySet();
    }

     List findCandidatesFor(String pattern, Function getter, List localizations) {
        String[] matchers = relationships().get(pattern);
        if (matchers == null) {
            throw new AssertionError("Unknown pattern: " + pattern);
        }
        if (matchers.length == 0) {
            return Collections.emptyList();
        }
        List candidates = new ArrayList<>(matchers.length);
        outer: for (String matcher : matchers) {
            for (T candidate : localizations) {
                String p = getter.apply(candidate);
                if (p.equals(matcher)) {
                    candidates.add(candidate);
                    continue outer;
                }
            }
        }
        return candidates;
    }

    private String[] candidates(ResourceBundle.Control ctrl, Locale l, String pattern) {
        List cl = ctrl.getCandidateLocales("", l);
        List list = new ArrayList<>(cl.size());
        for (Locale candidate : cl) {
            if (candidate.getLanguage().isEmpty()) {
                continue;
            }
            String candidatePattern = ctrl.toBundleName("", candidate);
            if (candidatePattern.equals(pattern)) {
                continue;
            }
            list.add(candidatePattern);
        }
        return list.toArray(new String[0]);
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy