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

ec.gob.senescyt.sniese.commons.clients.AbstractServicioCliente Maven / Gradle / Ivy

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

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.multipart.FormDataMultiPart;
import ec.gob.senescyt.sniese.commons.security.PrincipalProvider;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import java.io.Serializable;

public abstract class AbstractServicioCliente implements ServicioCliente {
    protected ServicioFactory factory;
    protected PrincipalProvider principalProvider;
    protected Client cliente;

    public AbstractServicioCliente(ServicioFactory factory, PrincipalProvider principalProvider) {
        this.factory = factory;
        this.principalProvider = principalProvider;
        this.cliente = Client.create();
    }

    @Override
    public ClientResponse get(String recurso, MultivaluedMap parametros) {
        WebResource.Builder builder = construirSolicitud(recurso, parametros);
        return builder.get(ClientResponse.class);
    }

    @Override
    public ClientResponse post(String recurso, Serializable entidad) {
        WebResource.Builder builder = construirSolicitud(recurso, null);
        return builder.post(ClientResponse.class, entidad);
    }

    @Override
    public ClientResponse multipartPost(final String recurso, FormDataMultiPart entidad) {
        return construirSolicitud(recurso, null)
                .type(MediaType.MULTIPART_FORM_DATA)
                .post(ClientResponse.class, entidad);
    }

    protected WebResource.Builder construirSolicitud(String recurso, MultivaluedMap parametros) {
        WebResource webResource = cliente.resource(factory.urlParaRecurso(recurso));
        if(parametros != null) {
            webResource = webResource.queryParams(parametros);
        }
        return webResource.header(AUTHORIZATION_HEADER, obtenerAuthToken())
                .accept(MediaType.APPLICATION_JSON_TYPE)
                .type(MediaType.APPLICATION_JSON_TYPE);
    }

    protected String obtenerAuthToken() {
        return principalProvider.obtenerUsuario() != null ? principalProvider.obtenerUsuario().getCredenciales() : factory.getToken();
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy