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

ec.gob.senescyt.sniese.commons.applications.AplicacionSniese Maven / Gradle / Ivy

There is a newer version: 2.0.5
Show newest version
package ec.gob.senescyt.sniese.commons.applications;

import com.google.common.annotations.VisibleForTesting;
import com.sun.jersey.api.core.ResourceConfig;
import ec.gob.senescyt.sniese.commons.configurations.ConfiguracionSnieseBase;
import ec.gob.senescyt.sniese.commons.exceptions.mappers.InvalidFormatExceptionMapper;
import ec.gob.senescyt.sniese.commons.exceptions.mappers.JsonMappingExceptionMapper;
import ec.gob.senescyt.sniese.commons.exceptions.mappers.MensajesErrorExceptionMapper;
import ec.gob.senescyt.sniese.commons.exceptions.mappers.ValidacionExceptionMapper;
import ec.gob.senescyt.sniese.commons.filters.HeaderResponseFilter;
import ec.gob.senescyt.sniese.commons.filters.RedireccionadorFilter;
import ec.gob.senescyt.sniese.commons.filters.SlashAlFinalFilter;
import io.dropwizard.jersey.setup.JerseyEnvironment;
import io.dropwizard.setup.Bootstrap;
import io.dropwizard.setup.Environment;
import org.eclipse.jetty.servlets.CrossOriginFilter;

import javax.servlet.DispatcherType;
import javax.servlet.FilterRegistration;
import javax.ws.rs.ext.ExceptionMapper;
import java.nio.charset.StandardCharsets;
import java.util.EnumSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

public class AplicacionSniese extends DecoradorAplicacion {

    public AplicacionSniese(DecoradorAplicacion siguiente) {
        super(siguiente);
    }

    @Override
    public void inicializar(Bootstrap bootstrap) {
        // Do nothing
    }

    @Override
    public void ejecutar(ConfiguracionSnieseBase configuracion, Environment ambiente) {
        registrarValidacionExceptionMappers(ambiente);
        registrarFiltros(configuracion, ambiente);
    }

    @VisibleForTesting
    public void registrarFiltros(ConfiguracionSnieseBase configuracion, Environment ambiente) {
        agregarFiltroSlashAlFinal(ambiente);
        agregarFiltroDeRespuesta(ambiente);
        agregarFiltroCors(ambiente);
        agregarFiltroDeRedireccion(configuracion, ambiente);
    }

    private void agregarFiltroCors(Environment ambiente) {
        final FilterRegistration.Dynamic dynamic = ambiente.servlets().addFilter("cors-filter", CrossOriginFilter.class);
        dynamic.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*");
        dynamic.setInitParameter(CrossOriginFilter.ALLOWED_HEADERS_PARAM, "X-Requested-With,Content-Type,Accept,Origin,Authorization");
        dynamic.setInitParameter(CrossOriginFilter.ALLOWED_METHODS_PARAM, "GET,POST,HEAD,PUT,DELETE,OPTIONS");
        dynamic.setInitParameter(CrossOriginFilter.ALLOWED_ORIGINS_PARAM, "*");
        dynamic.setInitParameter(CrossOriginFilter.ALLOW_CREDENTIALS_PARAM, "true");
    }

    private void agregarFiltroSlashAlFinal(Environment ambiente) {
        FilterRegistration.Dynamic filtro = ambiente.servlets().addFilter("slash-filter", SlashAlFinalFilter.class);
        filtro.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), true, "/*");
    }

    @SuppressWarnings("unchecked")
    private void agregarFiltroDeRespuesta(Environment environment) {
        final List containerResponseFilters = obtenerListaDeFiltrosDeRespuesta(environment);
        containerResponseFilters.add(new HeaderResponseFilter(StandardCharsets.UTF_8.name()));
    }

    private void agregarFiltroDeRedireccion(ConfiguracionSnieseBase configuracion, Environment ambiente) {
        final FilterRegistration.Dynamic filtro = ambiente.servlets().addFilter("redirect-filter", RedireccionadorFilter.class);
        filtro.setInitParameter("httpsPort", configuracion.getPuertoHttps());
        filtro.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), true, "/*");
    }

    private List obtenerListaDeFiltrosDeRespuesta(Environment environment) {
        final JerseyEnvironment jersey = environment.jersey();
        final ResourceConfig resourceConfig = jersey.getResourceConfig();
        return resourceConfig.getContainerResponseFilters();
    }

    @VisibleForTesting
    public void registrarValidacionExceptionMappers(Environment ambiente) {
        eliminarDefaultConstraintValidationMapper(ambiente);
        ambiente.jersey().register(new ValidacionExceptionMapper());
        ambiente.jersey().register(new MensajesErrorExceptionMapper());
        ambiente.jersey().register(new InvalidFormatExceptionMapper());
        ambiente.jersey().register(new JsonMappingExceptionMapper());
    }

    private void eliminarDefaultConstraintValidationMapper(Environment environment) {
        ResourceConfig jrConfig = environment.jersey().getResourceConfig();
        Set dwSingletons = jrConfig.getSingletons();

        List singletonsToRemove = dwSingletons
                .stream()
                .filter(s -> s instanceof ExceptionMapper &&
                        s.getClass().getName().equals("io.dropwizard.jersey.validation.ConstraintViolationExceptionMapper"))
                .collect(Collectors.toList());

        for (Object s : singletonsToRemove) {
            jrConfig.getSingletons().remove(s);
        }
    }

}