I18N { protected static Map<Entry, String> loadFromFile(String resourceLocation) { final ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader(); final InputStream is; if (new File(resourceLocation).isFile()) { try { is = Files.newInputStream(new File(resourceLocation).toPath()); } catch (IOException ie) { log.error("Exception while reading file {}", resourceLocation, ie); throw new RuntimeException(ie); } } else { is = systemClassLoader.getResourceAsStream(resourceLocation); } try (BufferedReader br = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8))) { Map<Entry, String> translations = new HashMap<>(1000); String line; boolean firstline = true; String[] languages = null, data; while ((line = br.readLine()) != null) { if (firstline) { languages = line.split(","); firstline = false; } else { data = line.split(","); String key = data[0].strip(); for (int i = 1; i < data.length; i++) { translations.put(new Entry(key, languages[i].strip()), data[i].strip()); } } } return translations; } catch (Exception e) { log.error("Exception while loading resource {}", resourceLocation, e); throw new RuntimeException(e); } } I18N(String resourcePath); String translate(String key, String language);  }
@Test void shouldLoadTranslationsFromResource() { final Map<I18N.Entry, String> translations = I18N.loadFromFile("data/multilinguism/translation.csv"); assert translations.size() == 6; }
@Test void shouldLoadTranslationsFromLocalFile() { final String file = System.getProperty("user.dir") + FILESEPARATOR + "src" + FILESEPARATOR + "test" + FILESEPARATOR + "resources" + FILESEPARATOR + "data" + FILESEPARATOR + "multilinguism" + FILESEPARATOR + "translation.csv"; final Map<I18N.Entry, String> translations = I18N.loadFromFile(file); assert translations.size() == 6; }
@Test void shouldThrowAnErrorWhenCantReadFromLocalFile() { final String file = System.getProperty("user.dir") + FILESEPARATOR + "src" + FILESEPARATOR + "test" + FILESEPARATOR + "resources" + FILESEPARATOR + "data" + FILESEPARATOR + "multilinguism" + FILESEPARATOR + "wrong.csv"; assertThrows(RuntimeException.class, () -> { I18N.loadFromFile(file); }); }
@Test void shouldThrowErrorWhenCantReadFromFile() { assertThrows(RuntimeException.class, () -> { I18N.loadFromFile("some/path/to.csv"); }); }