Skip to content
ListGroupsCall.java 1.76 KiB
Newer Older
package it.inaf.ia2.gms.client.call;

import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class ListGroupsCall extends BaseGmsCall {

    public ListGroupsCall(HttpClientWrapper clientWrapper) {
        super(clientWrapper);
    }

    /**
     * Returns the list of the groups in a given parent group (if the user has
     * the privileges to see that information). The prefix is removed by the
     * service.
     */
    public List<String> listGroups(String prefix) {

        List<String> groups = new ArrayList<>();

        String uri = "list";
        if (prefix != null && !prefix.isBlank()) {
            uri += "/" + prefix;
        }

        HttpRequest groupsRequest = newHttpRequest(uri)
                .header("Accept", "text/plain")
                .GET()
                .build();

        return getClient().sendAsync(groupsRequest, HttpResponse.BodyHandlers.ofInputStream())
                .thenApply(response -> {
                    if (response.statusCode() == 200) {
                        return response.body();
                    }
                    logServerErrorInputStream(groupsRequest, response);
                    throw new IllegalStateException("Unable to list groups");
                })
                .thenApply(inputStream -> {
                    try (Scanner scan = new Scanner(inputStream)) {
                        while (scan.hasNextLine()) {
                            String line = scan.nextLine();
                            if (!line.isEmpty()) {
                                groups.add(line);
                            }
                        }
                    }
                    return groups;
                }).join();
    }
}