Skip to content
RapClient.java 2.01 KiB
Newer Older
Sonia Zorba's avatar
Sonia Zorba committed
package it.inaf.ia2.gms.rap;

import it.inaf.ia2.gms.authn.SessionData;
import it.inaf.ia2.gms.model.RapUser;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
Sonia Zorba's avatar
Sonia Zorba committed
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
Sonia Zorba's avatar
Sonia Zorba committed

@Component
public class RapClient {

    @Value("${rap.ws-url}")
    private String rapBaseUrl;

    @Autowired
    private SessionData sessionData;

    @Autowired
    private RestTemplate rapRestTemplate;

    public List<RapUser> getUsers(Set<String> identifiers) {

        if (identifiers.isEmpty()) {
            return new ArrayList<>();
        }

        String url = rapBaseUrl + "/user?identifiers=" + String.join(",", identifiers);
        return rapRestTemplate.exchange(url, HttpMethod.GET, getEntity(), new ParameterizedTypeReference<List<RapUser>>() {
        }).getBody();
    }

    public List<RapUser> searchUsers(String searchText) {

        if (searchText == null || searchText.trim().isEmpty()) {
            return new ArrayList<>();
        }

        String url = rapBaseUrl + "/user?search=" + searchText;
        return rapRestTemplate.exchange(url, HttpMethod.GET, getEntity(), new ParameterizedTypeReference<List<RapUser>>() {
        }).getBody();
    }

    private HttpEntity<?> getEntity() {
        return getEntity(null);
    }

    private <T> HttpEntity<T> getEntity(T body) {

        HttpHeaders headers = new HttpHeaders();
        headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));

        headers.add("Authorization", "Bearer " + sessionData.getAccessToken());

        return new HttpEntity<>(body, headers);
    }