Path: blob/master/test/jdk/java/util/Currency/PropertiesTest.java
41149 views
/*1* Copyright (c) 2007, 2018, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*/2223import java.io.*;24import java.text.*;25import java.util.*;26import java.util.regex.*;27import java.util.stream.Collectors;2829public class PropertiesTest {30public static void main(String[] args) throws Exception {31if (args.length == 2 && args[0].equals("-d")) {32dump(args[1]);33} else if (args.length == 4 && args[0].equals("-c")) {34compare(args[1], args[2], args[3]);35} else if (args.length == 1 && args[0].equals("bug7102969")) {36bug7102969();37} else if (args.length == 1 && args[0].equals("bug8157138")) {38bug8157138();39} else if (args.length == 1 && args[0].equals("bug8190904")) {40bug8190904();41} else {42System.err.println("Usage: java PropertiesTest -d <dumpfile>");43System.err.println(" java PropertiesTest -c <beforedump> <afterdump> <propsfile>");44System.err.println(" java PropertiesTest bug[JBS bug id number] e.g. bug7102969");45System.exit(-1);46}47}4849private static void dump(String outfile) {50File f = new File(outfile);51PrintWriter pw;52try {53f.createNewFile();54pw = new PrintWriter(f);55} catch (Exception fnfe) {56throw new RuntimeException(fnfe);57}58for (char c1 = 'A'; c1 <= 'Z'; c1++) {59for (char c2 = 'A'; c2 <= 'Z'; c2++) {60String ctry = new StringBuilder().append(c1).append(c2).toString();61try {62Currency c = Currency.getInstance(new Locale("", ctry));63if (c != null) {64pw.printf(Locale.ROOT, "%s=%s,%03d,%1d\n",65ctry,66c.getCurrencyCode(),67c.getNumericCode(),68c.getDefaultFractionDigits());69}70} catch (IllegalArgumentException iae) {71// invalid country code72continue;73}74}75}76pw.flush();77pw.close();78}7980private static void compare(String beforeFile, String afterFile, String propsFile)81throws IOException82{83// load file contents84Properties before = new Properties();85try (Reader reader = new FileReader(beforeFile)) {86before.load(reader);87}88Properties after = new Properties();89try (Reader reader = new FileReader(afterFile)) {90after.load(reader);91}9293// remove the same contents from the 'after' properties94Set<String> keys = before.stringPropertyNames();95for (String key: keys) {96String beforeVal = before.getProperty(key);97String afterVal = after.getProperty(key);98System.out.printf("Removing country: %s. before: %s, after: %s", key, beforeVal, afterVal);99if (beforeVal.equals(afterVal)) {100after.remove(key);101System.out.printf(" --- removed\n");102} else {103System.out.printf(" --- NOT removed\n");104}105}106107// now look at the currency.properties108Properties p = new Properties();109try (Reader reader = new FileReader(propsFile)) {110p.load(reader);111}112113// test each replacements114keys = p.stringPropertyNames();115Pattern propertiesPattern =116Pattern.compile("([A-Z]{3})\\s*,\\s*(\\d{3})\\s*,\\s*" +117"(\\d+)\\s*,?\\s*(\\d{4}-\\d{2}-\\d{2}T\\d{2}:" +118"\\d{2}:\\d{2})?");119for (String key: keys) {120String val = p.getProperty(key);121try {122if (val.chars().map(c -> c == ',' ? 1 : 0).sum() >= 3123&& !isPastCutoverDate(val)) {124System.out.println("Skipping " + key + " since date is in future");125continue; // skip since date in future (no effect)126}127} catch (ParseException pe) {128// swallow - currency class should not honour this value129continue;130}131String afterVal = after.getProperty(key);132System.out.printf("Testing key: %s, val: %s... ", key, val);133System.out.println("AfterVal is : " + afterVal);134135if (afterVal == null) {136System.out.println("Testing key " + key + " is ignored"137+ " because of the inconsistent numeric code and/or"138+ " dfd for the given currency code: "+val);139continue;140}141142Matcher m = propertiesPattern.matcher(val.toUpperCase(Locale.ROOT));143if (!m.find()) {144// format is not recognized.145System.out.printf("Format is not recognized.\n");146if (afterVal != null) {147throw new RuntimeException("Currency data replacement for "+key+" failed: It was incorrectly altered to "+afterVal);148}149150// ignore this151continue;152}153154String code = m.group(1);155int numeric = Integer.parseInt(m.group(2));156int fraction = Integer.parseInt(m.group(3));157if (fraction > 9) {158System.out.println("Skipping since the fraction is greater than 9");159continue;160}161162Matcher mAfter = propertiesPattern.matcher(afterVal);163mAfter.find();164165String codeAfter = mAfter.group(1);166int numericAfter = Integer.parseInt(mAfter.group(2));167int fractionAfter = Integer.parseInt(mAfter.group(3));168if (code.equals(codeAfter) &&169(numeric == numericAfter)&&170(fraction == fractionAfter)) {171after.remove(key);172} else {173throw new RuntimeException("Currency data replacement for "+key+" failed: actual: (alphacode: "+codeAfter+", numcode: "+numericAfter+", fraction: "+fractionAfter+"), expected: (alphacode: "+code+", numcode: "+numeric+", fraction: "+fraction+")");174}175System.out.printf("Success!\n");176}177if (!after.isEmpty()) {178179keys = after.stringPropertyNames();180for (String key : keys) {181String modified = after.getProperty(key);182if(!p.containsValue(modified)) {183throw new RuntimeException("Unnecessary modification was"184+ " made to county: "+ key + " with currency value:"185+ " " + modified);186} else {187System.out.println(key + " modified by an entry in"188+ " currency.properties with currency value "189+ modified);190}191}192}193}194195private static void bug7102969() {196// check the correct overriding of special case entries197Currency cur = Currency.getInstance(new Locale("", "JP"));198if (!cur.getCurrencyCode().equals("ABC")) {199throw new RuntimeException("[Expected: ABC as currency code of JP, found: "200+ cur.getCurrencyCode() + "]");201}202203/* check if the currency instance is returned by204* getAvailableCurrencies() method205*/206if (!Currency.getAvailableCurrencies().contains(cur)) {207throw new RuntimeException("[The Currency instance ["208+ cur.getCurrencyCode() + ", "209+ cur.getNumericCode() + ", "210+ cur.getDefaultFractionDigits()211+ "] is not available in the currencies list]");212}213214}215216private static void bug8157138() {217218/* check the currencies which exist only as a special case are219* accessible i.e. it should not throw IllegalArgumentException220*/221try {222Currency.getInstance("MAD");223} catch (IllegalArgumentException ex) {224throw new RuntimeException("Test Failed: "225+ "special case currency instance MAD not found"226+ " via Currency.getInstance(\"MAD\")");227}228229try {230Currency.getInstance("ABC");231} catch (IllegalArgumentException ex) {232throw new RuntimeException("Test Failed: "233+ "special case currency instance ABC not found"234+ " via Currency.getInstance(\"ABC\")");235}236237/* check the currency value is returned by getAvailableCurrencies()238* method239*/240List<Currency> list = Currency.getAvailableCurrencies().stream()241.filter(cur -> cur.getCurrencyCode().equals("MAD"))242.collect(Collectors.toList());243244if (list.isEmpty()) {245throw new RuntimeException("Test Failed: "246+ "special case currency instance MAD not found"247+ " in Currency.getAvailableCurrencies() list");248}249250list = Currency.getAvailableCurrencies().stream()251.filter(cur -> cur.getCurrencyCode().equals("ABC"))252.collect(Collectors.toList());253254if (list.isEmpty()) {255throw new RuntimeException("Test Failed: "256+ "special case currency instance ABC not found"257+ " in Currency.getAvailableCurrencies() list");258}259260}261262private static void bug8190904() {263// should throw IllegalArgumentException as currency code264// does not exist as valid ISO 4217 code and failed to load265// from currency.properties file because of inconsistent numeric/dfd266try {267Currency.getInstance("MCC");268throw new RuntimeException("[FAILED: Should throw"269+ " IllegalArgumentException for invalid currency code]");270} catch (IllegalArgumentException ex) {271// expected to throw IllegalArgumentException272}273274// should keep the XOF instance as XOF,952,0, as the XOF entries in275// currency.properties IT=XOF,952,1, XY=XOF,955,0 are ignored because276// of inconsistency in numeric code and/or dfd277checkCurrencyInstance("XOF", 952, 0);278// property entry "AS=USD,841,2" should change all occurences279// of USD with USD,841,2280checkCurrencyInstance("USD", 841, 2);281}282283/**284* Test the numeric code and fraction of the Currency instance obtained285* by given currencyCode, with the expected numericCode and fraction286*/287private static void checkCurrencyInstance(String currencyCode,288int numericCode, int fraction) {289Currency cur = Currency.getInstance(currencyCode);290if (cur.getNumericCode() != numericCode291|| cur.getDefaultFractionDigits() != fraction) {292throw new RuntimeException("[FAILED: Incorrect numeric code or"293+ " dfd for currency code: " + currencyCode + "]");294}295}296297private static boolean isPastCutoverDate(String s)298throws IndexOutOfBoundsException, NullPointerException, ParseException {299String dateString = s.substring(s.lastIndexOf(',')+1, s.length()).trim();300SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.ROOT);301format.setTimeZone(TimeZone.getTimeZone("GMT"));302format.setLenient(false);303304long time = format.parse(dateString).getTime();305if (System.currentTimeMillis() - time >= 0L) {306return true;307} else {308return false;309}310}311312}313314315