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

fr.ird.observe.validation.ValidatorsManager Maven / Gradle / Ivy

There is a newer version: 4.34
Show newest version
package fr.ird.observe.validation;

/*-
 * #%L
 * ObServe Toolkit :: Common Validation
 * %%
 * Copyright (C) 2017 - 2020 IRD, Ultreia.io
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU 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 Public License for more details.
 *
 * You should have received a copy of the GNU General Public
 * License along with this program.  If not, see
 * .
 * #L%
 */

import com.google.common.collect.ImmutableSet;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import fr.ird.observe.dto.ObserveDto;
import fr.ird.observe.gson.ClassAdapter;
import io.ultreia.java4all.application.context.spi.GenerateApplicationComponent;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collection;

/**
 * Created by tchemit on 05/08/17.
 *
 * @author Tony Chemit - [email protected]
 */
@GenerateApplicationComponent(name = "ObServe Validators manager")
public class ValidatorsManager implements ObserveDto {

    private static final String RESOURCE_VALIDATORS = "/META-INF/validators/validation.json";

    private final ImmutableSet validators;

    public ValidatorsManager(Collection validators) {
        this.validators = ImmutableSet.copyOf(validators);
    }

    public ValidatorsManager() {
        try (Reader reader = new InputStreamReader(getClass().getResourceAsStream(RESOURCE_VALIDATORS))) {
            ValidatorDto[] validators = getGson().fromJson(reader, ValidatorDto[].class);
            this.validators = ImmutableSet.copyOf(validators);
        } catch (Exception e) {
            throw new ValidatorInitializationException(e);
        }
    }

    public ImmutableSet getValidators() {
        return validators;
    }

    public void store(Path target) throws IOException {
        String validatorsJson = getGson().toJson(validators.toArray(new ValidatorDto[0]), ValidatorDto[].class);
        Files.write(target, validatorsJson.getBytes(StandardCharsets.UTF_8));
    }

    protected Gson getGson() {
        return new GsonBuilder().setPrettyPrinting().registerTypeAdapter(Class.class, new ClassAdapter()).create();
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy