io.ultreia.java4all.i18n.spi.I18nKeySetDefinition Maven / Gradle / Ivy
package io.ultreia.java4all.i18n.spi;
/*-
* #%L
* I18n :: Spi
* %%
* Copyright (C) 2018 Code Lutin, Ultreia.io
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* .
* #L%
*/
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
/**
* Describe a set of i18n keys used by a module.
*
* Created by tchemit on 26/10/2018.
*
* @author Tony Chemit - [email protected]
*/
public class I18nKeySetDefinition extends I18nResource {
public static String KEY_SET_EXTENSION = ".getter";
public I18nKeySetDefinition(String packageName, String name) {
super(packageName, name, KEY_SET_EXTENSION);
}
public I18nKeySetDefinition(I18nCoordinate coordinate) {
super(coordinate, KEY_SET_EXTENSION);
}
public static I18nKeySetDefinition newKey(String coordinate) {
String[] split = Objects.requireNonNull(coordinate).split(":");
return new I18nKeySetDefinition(split[0], split[1]);
}
public static I18nKeySetDefinition newKeyFromPath(String packageName, Path coordinate) {
return newKey(packageName + ":" + removeExtension(coordinate.toFile().getName(), KEY_SET_EXTENSION));
}
public static List detect(Path directory, String packageName) throws I18nResourceInitializationException {
if (!Files.exists(directory)) {
return Collections.emptyList();
}
String extension = I18nKeySetDefinition.KEY_SET_EXTENSION;
try {
return Files
.walk(directory, 1)
.filter(p -> Files.isRegularFile(p) && p.toFile().getName().endsWith(extension))
.map(f -> I18nKeySetDefinition.newKeyFromPath(packageName, f))
.collect(Collectors.toList());
} catch (Exception e) {
throw new I18nResourceInitializationException("Can't detect key sets from directory: " + directory, e);
}
}
public static Path write(I18nKeySetDefinition definition, Path directory, Charset encoding, boolean usePackage, Set keys) throws IOException {
if (!Files.exists(Objects.requireNonNull(directory))) {
Files.createDirectories(directory);
}
String fileName = definition.getResourcePath(usePackage);
Path target = directory.resolve(fileName);
Files.write(target, keys, encoding);
return target;
}
}