All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.nuiton.i18n.plugin.I18nMojoHelper Maven / Gradle / Ivy

Go to download

Maven plugin to deal with i18n stuff in a project, mainly base on the i18n api (but not only).

There is a newer version: 4.0-beta-28
Show newest version
package org.nuiton.i18n.plugin;

/*-
 * #%L
 * I18n :: Maven Plugin
 * %%
 * Copyright (C) 2007 - 2024 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 io.ultreia.java4all.i18n.spi.I18nResource;
import io.ultreia.java4all.i18n.spi.builder.I18nKeySet;
import io.ultreia.java4all.i18n.spi.builder.I18nTemplate;
import io.ultreia.java4all.i18n.spi.builder.I18nTranslationSet;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugin.logging.Log;
import org.nuiton.i18n.plugin.bundle.BundleValidation;
import org.nuiton.plugin.PluginHelper;

import java.io.File;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;

/**
 * Created by tchemit on 30/10/2018.
 *
 * @author Tony Chemit - [email protected]
 */
public class I18nMojoHelper {

    private final Log log;
    private final boolean silent;
    private final boolean verbose;

    public I18nMojoHelper(Log log, boolean silent, boolean verbose) {

        this.log = log;
        this.silent = silent;
        this.verbose = verbose;
    }

    public Set keySetToStr(List list, String message) {
        Set result = new LinkedHashSet<>();
        if (!list.isEmpty()) {
            StringBuilder messageBuilder = new StringBuilder();
            for (I18nKeySet dependenciesGetter : list) {
                String id = dependenciesGetter.getDefinition().getId();
                result.add(id);
                int size = dependenciesGetter.size();
                messageBuilder.append(String.format("\n\t%s (%d keys)", id, size));
            }
            log.info(String.format(message, result.size(), messageBuilder.toString()));
        }
        return result;
    }

    public Set translationsToStr(List list, String message) {
        Set result = new LinkedHashSet<>();
        if (!list.isEmpty()) {
            Map> map = new LinkedHashMap<>();
            StringBuilder messageBuilder = new StringBuilder();
            for (I18nTranslationSet moduleTranslation : list) {
                String id = moduleTranslation.getDefinition().getId();
                List strings = map.computeIfAbsent(id, k -> new LinkedList<>());
                String locale = moduleTranslation.getDefinition().getLocale().toString();
                strings.add(locale);
                int size = moduleTranslation.getTranslations().size();
                messageBuilder.append(String.format("\n\t%s (%d sentences)", id + "_" + locale, size));
            }
            int count = 0;
            for (Map.Entry> entry : map.entrySet()) {
                List locales = entry.getValue();
                count += locales.size();
                result.add(entry.getKey() + I18nResource.GROUP_ID_SEPARATOR + String.join(I18nResource.GROUP_ID_SEPARATOR, locales));
            }

            log.info(String.format(message, count, messageBuilder.toString()));
        }
        return result;
    }

    public Set templatesToStr(List list, String message) {
        Set result = new LinkedHashSet<>();
        if (!list.isEmpty()) {
            Map> map = new LinkedHashMap<>();
            StringBuilder messageBuilder = new StringBuilder();
            for (I18nTemplate moduleTemplate : list) {
                String id = moduleTemplate.getDefinition().getId();
                List strings = map.computeIfAbsent(id, k -> new LinkedList<>());
                String locale = moduleTemplate.getDefinition().getLocale().toString();
                strings.add(locale);
                messageBuilder.append(String.format("\n\t%s", id + "_" + locale));
            }
            int count = 0;
            for (Map.Entry> entry : map.entrySet()) {
                List locales = entry.getValue();
                count += locales.size();
                result.add(entry.getKey() + I18nResource.GROUP_ID_SEPARATOR + String.join(I18nResource.GROUP_ID_SEPARATOR, locales));
            }
            log.info(String.format(message, count, messageBuilder.toString()));
        }
        return result;
    }

    public void checkBundle(Locale locale,
                            Properties propertiesOut,
                            boolean showEmpty,
                            BundleValidation bundleValidation) {

        // on verifie qu'il n'y a pas de traduction vide
        SortedSet emptyEntries = PluginHelper.getEmptyKeys(propertiesOut);
        if (!emptyEntries.isEmpty()) {
            if (bundleValidation != null) {
                Map> unsafeHolder = bundleValidation.getKeysMissingValues();
                // push empties i18n keys in the holder
                SortedSet empties = unsafeHolder.computeIfAbsent(locale, k -> new TreeSet<>());
                empties.addAll(emptyEntries);
            }
            StringBuilder buffer = new StringBuilder();
            int size = emptyEntries.size();
            buffer.append("bundle ");
            buffer.append(locale);
            buffer.append(" contains ");
            buffer.append(size);
            buffer.append("/");
            buffer.append(propertiesOut.size());
            buffer.append(" empty entries!");
            if (showEmpty) {
                int index = 0;
                for (String key : emptyEntries) {
                    buffer.append("\n  - ");
                    buffer.append(index++);
                    buffer.append("/");
                    buffer.append(size);
                    buffer.append(" : ");
                    buffer.append(key);
                }
            } else {
                buffer.append(" (use -Di18n.showEmpty to see these entries)");
            }
            getLog().warn(buffer.toString());
        } else {
            if (!silent && verbose) {
                getLog().info(String.format("bundle %s is valid (no empty entries).", locale));
            }
        }
    }

    public void failsIfAnyKeyMissingValue(boolean failsIfWarning, BundleValidation bundleValidation) throws MojoFailureException {
        if (!failsIfWarning) {

            // no check
            return;
        }

        if (bundleValidation != null && bundleValidation.isAnyKeyMissingValue()) {

            // there is at least one not complete bundle, fails the build
            throw new MojoFailureException(
                    String.format("Bundles for locale(s) %s are not complete. Use the -Di18n.showEmpty to see missing translations.", bundleValidation.getKeysMissingValues().keySet()));
        }
    }

    public void failsIfAnyKeyMissingInBundle(boolean failsIfWarning, BundleValidation bundleValidation) throws MojoFailureException {
        if (!failsIfWarning) {

            // no check
            return;
        }

        if (bundleValidation != null && bundleValidation.isAnyKeyMissingInBundle()) {

            // there is at least one not complete bundle, fails the build
            throw new MojoFailureException(
                    String.format("Bundles for locale(s) %s are not complete. Use the -Di18n.showEmpty to see missing keys.", bundleValidation.getMissingKeysPerLocale().keySet()));
        }
    }


    /**
     * @param root       le repertoire ou sont stockes les fichiers i18n
     * @param artifactId le nom de l'artifact
     * @param locale     le nom de la locale (peut-être nulle)
     * @param create     {@code true} pour creer le fichier si non present
     * @return le fichier i18n
     * @throws IOException si probleme lors de la creation du fichier
     */
    public File getI18nFile(File root, String artifactId, Locale locale, boolean create) throws IOException {
        String path = root.getAbsolutePath() + File.separatorChar + artifactId;
        if (locale != null) {
            path += "_" + locale.toString();
        }
        path += ".properties";
        File file = new File(path);
        if (create && !file.exists()) {
            PluginHelper.createNewFile(file);
        }
        return file;
    }

    public Log getLog() {
        return log;
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy