下面列出了java.util.ResourceBundle#keySet ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private static void logConfigurations(ResourceBundle configs){
if(configs == null){
return;
}
StringBuilder configString = new StringBuilder();
for(String key: configs.keySet()){
if(!key.contains("secretkey")){
configString.append("\n\t")
.append(key)
.append(": ")
.append(configs.getString(key));
}
}
POCLogger.logp(Level.FINE, CLASSNAME, "logConfigurations", "POC-MSG-1000", configString.toString());
}
private static void logConfigurations(ResourceBundle configs){
if(configs == null){
return;
}
StringBuilder configString = new StringBuilder();
for(String key: configs.keySet()){
if(!key.contains("secretkey")){
configString.append("\n\t")
.append(key)
.append(": ")
.append(configs.getString(key));
}
}
WebauthnTutorialLogger.logp(Level.FINE, CLASSNAME, "logConfigurations", "WEBAUTHN-MSG-1000", configString.toString());
}
@CheckForNull
private JSONObject getBundle(BundleParams bundleParams, Locale locale) {
PluginWrapper plugin = bundleParams.getPlugin();
if (plugin == null) {
return null;
}
try {
ResourceBundle resourceBundle = ResourceBundle.getBundle(bundleParams.bundleName, locale, plugin.classLoader);
JSONObject bundleJSON = new JSONObject();
for (String key : resourceBundle.keySet()) {
bundleJSON.put(key, resourceBundle.getString(key));
}
return bundleJSON;
} catch (MissingResourceException e) {
// fall through and return null.
}
return null;
}
private static void makeIndicesComposite(JanusGraphManagement management) {
ResourceBundle keys = ResourceBundle.getBundle("resources/indices-composite");
Set<String> keyString = keys.keySet();
for (String propertyKeyLabel : keyString) {
String indexLabel = "by" + propertyKeyLabel;
JanusGraphIndex index = management.getGraphIndex(indexLabel);
if (index == null) {
boolean isUnique = Boolean.parseBoolean(keys.getString(propertyKeyLabel));
PropertyKey key = management.getPropertyKey(propertyKeyLabel);
JanusGraphManagement.IndexBuilder indexBuilder = management.buildIndex(indexLabel, Vertex.class).addKey(key);
if (isUnique) {
indexBuilder.unique();
}
indexBuilder.buildCompositeIndex();
}
}
}
/**
* Default constructor
*/
public ConfigurationServiceImpl() {
this.propertyHolder.getHeldProperties().putAll(ConfigContext.getCurrentContextConfig().getProperties());
// TODO: remove loading of property files once KNS legacy code is removed
String propertyConfig = (String) ConfigContext.getCurrentContextConfig().getProperties().get(MESSAGE_RESOURCES);
propertyConfig = removeSpacesAround(propertyConfig);
String[] bundleNames = StringUtils.split(propertyConfig, ",");
for (String bundleName : bundleNames) {
ResourceBundle bundle = ResourceBundle.getBundle(bundleName);
for (String key : bundle.keySet()) {
String message = bundle.getString(key);
this.propertyHolder.getHeldProperties().put(key, message);
}
}
}
private ValueMap<? extends LanguageTermDefinition> readLangs(Locale locale) {
ArrayList<LangTermValue> langs = new ArrayList<LangTermValue>();
// to read properties file in UTF-8 use PropertyResourceBundle(Reader)
Control control = ResourceBundle.Control.getNoFallbackControl(ResourceBundle.Control.FORMAT_PROPERTIES);
ResourceBundle rb = ResourceBundle.getBundle(BundleName.LANGUAGES_ISO639_2.toString(), locale, control);
for (String key : rb.keySet()) {
LangTermValue lt = new LangTermValue();
lt.setAuthority("iso639-2b");
lt.setType(CodeOrText.CODE);
lt.setValue(key);
lt.setTitle(rb.getString(key));
langs.add(lt);
}
Collections.sort(langs, new LangComparator(locale));
return new ValueMap<LangTermValue>(BundleName.LANGUAGES_ISO639_2.getValueMapId(), langs);
}
/**
* 获取指定前辍对应的所有的Message集合
*
* @param locale @see Locale
* @param codePrefixes code前辍
* @return Map[Key, Value]
*/
public Map<String, String> getMessages(final Locale locale, final String... codePrefixes) {
final Map<String, String> messagesMap = new HashMap<>(128);
if (ArrayUtils.isEmpty(codePrefixes)) {
return messagesMap;
}
final Set<String> basenames = this.getBasenameSet();
for (final String basename : basenames) {
final ResourceBundle bundle = getResourceBundle(basename, locale);
if (bundle != null) {
for (final String key : bundle.keySet()) {
if (StringUtils.startsWithAny(key, codePrefixes)) {
messagesMap.put(key, bundle.getString(key));
}
}
}
}
return messagesMap;
}
/**
* Loads translation keys of a locale.
*
* @param locale A locale.
* @return The number of keys found, or 0 if already loaded.
*/
public static long loadKeys(Locale locale) {
if (getLocales().contains(locale)) return 0;
long keysFound = 0;
for (String resourceName : SOURCE_NAMES) {
// If the locale is not the source code locale,
// then append the language tag to get the proper resource
if (locale != SOURCE_LOCALE)
resourceName += "_" + locale.toLanguageTag().replaceAll("-", "_");
final ResourceBundle resource;
try {
resource = ResourceBundle.getBundle(resourceName, locale, SOURCE_CONTROL);
} catch (MissingResourceException e) {
continue;
}
for (String key : resource.keySet()) {
String format = resource.getString(key);
// Single quotes are a special keyword that need to be escaped in MessageFormat
// Templates are not escaped, where as translations are escaped
if (locale == SOURCE_LOCALE) format = format.replaceAll("'", "''");
TRANSLATIONS_TABLE.put(key, locale, new MessageFormat(format, locale));
keysFound++;
}
}
// Clear locale cache when a new locale is loaded
if (keysFound > 0) {
LOCALES.clear();
}
return keysFound;
}
public void testReadResource1() {
ResourceBundle bundle = ResourceBundle.getBundle("sun.security.util.Resources");
Set<String> strings = bundle.keySet();
System.out.println(strings);
Enumeration<String> keys = bundle.getKeys();
int i = 0;
while (keys.hasMoreElements()) {
String s = keys.nextElement();
System.out.println(i + ": " + s);
i++;
}
}
@Test
void testKeyName() {
ResourceBundle defaultBundle = Utils.getResourceBundle(null);
Set<String> defaultSet = defaultBundle.keySet();
for (String lang : Utils.getSupportedLanguages()) {
if (lang.equals(DEFAULT_LANG))
continue;
for (String key : Utils.getResourceBundle(lang).keySet()) {
assertTrue(defaultSet.contains(key),
String.format("The key %s of %s is not in the default bundle", key, lang));
}
}
}
@Override
protected Set<String> handleKeySet() {
if (keys == null) {
ResourceBundle info = getBreakIteratorInfo();
Set<String> k = info.keySet();
k.removeAll(NON_DATA_KEYS);
synchronized (this) {
if (keys == null) {
keys = k;
}
}
}
return keys;
}
@Override
protected Set<String> handleKeySet() {
if (keys == null) {
ResourceBundle info = getBreakIteratorInfo();
Set<String> k = info.keySet();
k.removeAll(NON_DATA_KEYS);
synchronized (this) {
if (keys == null) {
keys = k;
}
}
}
return keys;
}
private Set<String> getKeysFromFile(
Map<String, ResourceBundle> defaultMessageProperties,
Map<String, Properties> localizedProperties, String locale,
String sheetName) {
if (BaseBean.LABEL_USERINTERFACE_TRANSLARIONS.equals(sheetName)) {
ResourceBundle bundle = defaultMessageProperties.get(locale);
if (bundle != null) {
return bundle.keySet();
}
} else {
return loadKeySetFromProperties(localizedProperties, locale
+ StandardLanguage.COLUMN_HEADING_SUFFIX);
}
return new HashSet<String>();
}
@Test
public void allMessageTagsPresent() {
ResourceBundle bundle = ResourceBundle.getBundle("dss-messages", Locale.getDefault());
Set<String> keySet = bundle.keySet();
assertNotNull(keySet);
assertTrue(keySet.size() > 0);
MessageTag[] messageTags = MessageTag.values();
for (String key : keySet) {
assertTrue(Arrays.stream(messageTags).anyMatch(tag -> tag.getId().equals(key)), "MessageTag with a key [" + key + "] does not exist!");
}
}
private static void copyParameters(String prefix, BaseConfiguration config,
ResourceBundle bundle) {
for (String key : bundle.keySet()) {
if (key.startsWith(prefix)) {
config.setParameter(key, bundle.getString(key));
}
}
}
private ArrayList<Item> readBundle(BundleName bundleName, Locale localeObj, Control control, boolean sorted) {
// to read properties file in UTF-8 use PropertyResourceBundle(Reader)
ResourceBundle rb = ResourceBundle.getBundle(bundleName.toString(), localeObj, control);
ArrayList<Item> result = new ArrayList<Item>();
for (String key : rb.keySet()) {
result.add(new Item(key, rb.getString(key), bundleName.toString()));
}
if (sorted) {
Collections.sort(result, new LocalizedItemComparator(localeObj));
}
return result;
}
private boolean addItemsToBuilder(LionBundle.Builder builder,
LionConfig.CmdFrom from) {
String resBundleName = base + SLASH + from.res();
String fqbn = convertToFqbn(resBundleName);
ResourceBundle bundle = null;
boolean ok = true;
try {
// NOTE: have to be explicit about the locale and class-loader
// for this to work under Karaf, apparently...
Locale locale = Locale.getDefault();
ClassLoader classLoader = getClass().getClassLoader();
bundle = LionUtils.getBundledResource(fqbn, locale, classLoader);
} catch (MissingResourceException e) {
log.warn("Cannot find resource bundle: {}", fqbn);
log.debug("BOOM!", e);
ok = false;
}
if (ok) {
Set<String> keys = from.starred() ? bundle.keySet() : from.keys();
addItems(builder, bundle, keys);
log.debug(" added {} item(s) from {}", keys.size(), from.res());
}
return ok;
}
public Set<String> getKeys(String basename, Locale locale) {
ResourceBundle bundle = getResourceBundle(basename, locale);
if (bundle == null) return Collections.EMPTY_SET;
return bundle.keySet();
}
/**
* This method does the processing and preparation of the data to be added
* to the Velocity context so that the macro can access and process the data
*
* The given messageKey (e.g. 'BRK') uses a 3-digit code used to match
* the property key from the loaded 'LogMessages' ResourceBundle.
*
* This gives a list of messages which are to be associated with the given
* messageName (e.g. 'Broker')
*
* Each of the messages in the list are then processed to identify how many
* parameters the MessageFormat call is expecting. These parameters are
* identified by braces ('{}') so a quick count of these can then be used
* to create a defined parameter list.
*
* Rather than defaulting all parameters to String a check is performed to
* see if a 'number' value has been requested. e.g. {0. number}
* {@see MessageFormat}. If a parameter has a 'number' type then the
* parameter will be defined as an Number value. This allows for better
* type checking during compilation whilst allowing the log message to
* maintain formatting controls.
*
* OPTIONS
*
* The returned hashMap contains the following structured data:
*
* - name - ClassName ('Broker')
* - list[logEntryData] - methodName ('BRK_1001')
* - name ('BRK-1001')
* - format ('Startup : Version: {0} Build: {1}')
* - parameters (list)
* - type ('String'|'Number')
* - name ('param1')
* - options (list)
* - name ('opt1')
* - value ('AutoDelete')
*
* @param messsageName the name to give the Class e.g. 'Broker'
*
* @return A HashMap with data for the macro
*
* @throws InvalidTypeException when an unknown parameter type is used in the properties file
*/
private HashMap<String, Object> prepareType(String messsageName, ResourceBundle messages) throws InvalidTypeException
{
// Load the LogMessages Resource Bundle
Set<String> messageKeys = new TreeSet<>(messages.keySet());
//Create the return map
HashMap<String, Object> messageTypeData = new HashMap<String, Object>();
// Store the name to give to this Class <name>Messages.java
messageTypeData.put("name", messsageName);
// Prepare the list of log messages
List<HashMap> logMessageList = new LinkedList<HashMap>();
messageTypeData.put("list", logMessageList);
//Process each of the properties
for(String message : messageKeys)
{
HashMap<String, Object> logEntryData = new HashMap<String, Object>();
// Process the log message if it matches the specified key e.g.'BRK_'
if (!message.equals("package"))
{
// Method names can't have a '-' in them so lets make it '_'
// e.g. RECOVERY-STARTUP -> RECOVERY_STARTUP
logEntryData.put("methodName", message.replace('-', '_'));
// Store the real name so we can use that in the actual log.
logEntryData.put("name", message);
//Retrieve the actual log message string.
String logMessage = messages.getString(message);
// Store the value of the property so we can add it to the
// Javadoc of the method.
logEntryData.put("format", logMessage);
// Add the parameters for this message
logEntryData.put("parameters", extractParameters(logMessage));
//Add the options for this messages
logEntryData.put("options", extractOptions(logMessage));
//Add this entry to the list for this class
logMessageList.add(logEntryData);
}
}
return messageTypeData;
}
/**
* 获取配置文件参数
*
* @param name
* @return
*/
public static final Map<Object, Object> getConfigMap(String path) {
ResourceBundle bundle = ResourceBundle.getBundle(path);
Set set = bundle.keySet();
return oConvertUtils.SetToMap(set);
}