1/* 2 * Copyright (c) 2015, 2017, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. 8 * 9 * This code is distributed in the hope that it will be useful, but WITHOUT 10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 12 * version 2 for more details (a copy is included in the LICENSE file that 13 * accompanied this code). 14 * 15 * You should have received a copy of the GNU General Public License version 16 * 2 along with this work; if not, write to the Free Software Foundation, 17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 18 * 19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 20 * or visit www.oracle.com if you need additional information or have any 21 * questions. 22 */ 23 24package jdk.test.resources.spi; 25 26import java.io.BufferedInputStream; 27import java.io.InputStream; 28import java.io.IOException; 29import java.util.Enumeration; 30import java.util.Locale; 31import java.util.Properties; 32import java.util.ResourceBundle; 33import java.util.spi.ResourceBundleProvider; 34 35public class MyResourcesProvider implements ResourceBundleProvider { 36 @Override 37 public ResourceBundle getBundle(String baseName, Locale locale) { 38 String xmlName = toXMLName(baseName, locale); 39 try (InputStream is = this.getClass().getModule().getResourceAsStream(xmlName)) { 40 return new XMLResourceBundle(new BufferedInputStream(is)); 41 } catch (IOException e) { 42 throw new RuntimeException(e); 43 } 44 } 45 46 private String toXMLName(String baseName, Locale locale) { 47 StringBuilder sb = new StringBuilder(baseName.replace('.', '/')); 48 String lang = locale.getLanguage(); 49 if (!lang.isEmpty()) { 50 sb.append('_').append(lang); 51 String country = locale.getCountry(); 52 if (!country.isEmpty()) { 53 sb.append('_').append(country); 54 } 55 } 56 return sb.append(".xml").toString(); 57 } 58 59 private static class XMLResourceBundle extends ResourceBundle { 60 private Properties props; 61 62 XMLResourceBundle(InputStream stream) throws IOException { 63 props = new Properties(); 64 props.loadFromXML(stream); 65 } 66 67 @Override 68 protected Object handleGetObject(String key) { 69 if (key == null) { 70 throw new NullPointerException(); 71 } 72 return props.get(key); 73 } 74 75 @Override 76 public Enumeration<String> getKeys() { 77 // Not implemented 78 return null; 79 } 80 } 81} 82