Like what you see? Have a play with our trial version.

Error rendering macro 'rw-search'

null

Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Members of existing groups can be returned using the GET /api/user-groups/{groupId}/members end-point (https://developers.yellowfinbi.com/dev/api-docs/current/#operation/getUserGroupMemberList ). Get User Group Member List. This service will return the components of a group. For example, this will return a Group or Role as a member, and not the users that those components represent. There is a separate end-point for getting the final flattened member list, where the individual users within a group or role are retrieved.

The following examples return the JSON payload representing a list of group member components in various programming languages.

Java | C# | Go | JavaScript | PHP | Python

List Group Members (Flattened)

Members of existing groups can be returned using the GET /api/user-groups/{groupId}/flat-users end-point (https://developers.yellowfinbi.com/dev/api-docs/current/#operation/getUserGroupFlatUserList ). This service will return the individual user members of a group. This service will return an expanded list of users that may have been included by group member components that represent multiple users, like other groups, roles or LDAP groups. 

The following example returns the JSON payload representing a list of group member components.

These code examples use Apache HTTP Client and GSON for handling REST calls and JSON serialization.

...

Code Block
languagejava
titleJava
collapsetrue
package rest.code.examples;
import java.io.IOException;
import java.util.Random;
import org.apache.hc.client5.http.fluent.Content;
import org.apache.hc.client5.http.fluent.Request;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
/**
 * Create a user using the Yellowfin REST API
 */
public class ListGroupMembers {
    public static void main(String[] args) throws Exception {

        System.out.println(""List Group Member Components"");

        String host = ""http://localhost:8080/Yellowfin"";
        String restUsername = ""admin@yellowfin.com.au"";
        String restPassword = ""test"";

        String groupName = ""New Group"";

        String token = generateToken(host, restUsername, restPassword);

        Integer groupId = retrieveGroupIpIdForGroupName(host, token, groupName);

        Content c = Request.get(host + ""/api/user-groups/"" + groupId + ""/members"")
                .addHeader(""Authorization"", ""YELLOWFIN ts="" + System.currentTimeMillis() + "" , nonce="" + new Random().nextLong() + "", token="" + token)
                .addHeader(""Accept"", ""application/vnd.yellowfin.api-v1+json"")
                .addHeader(""Content-Type"", ""application/json"")
                .execute().returnContent();

        System.out.println(c.toString());

    }


    public static Integer retrieveGroupIpIdForGroupName(String host, String token, String groupName) throws IOException {

        Content c = Request.get(host + ""/api/user-groups"")
                .addHeader(""Authorization"", ""YELLOWFIN ts="" + System.currentTimeMillis() + "" , nonce="" + new Random().nextLong() + "", token="" + token)
                .addHeader(""Accept"", ""application/vnd.yellowfin.api-v1+json"")
                .addHeader(""Content-Type"", ""application/json"")
                .execute().returnContent();

        JsonObject jsonObject = new JsonParser().parse(c.asString()).getAsJsonObject();
        JsonElement groupList = jsonObject.get(""items"");
        JsonArray groups = groupList.getAsJsonArray();

        for (int i=0; i < groups.size(); i++ ) {
            JsonObject group = groups.getAsJsonArray().get(i).getAsJsonObject();
            if (groupName.equals(group.get(""shortDescription"").getAsString())) return group.get(""userGroupId"").getAsInt();
        }

        System.out.println(""Group could not be found for name:"" + groupName);
        System.exit(-1);

        return null;
    }

    /*
     *  This function generates an access token for a user that will grant them access to
     *  call REST API endpoints.
     */

    public static String generateToken(String host, String username, String password) throws IOException {

        Content c = Request.post(host + ""/api/refresh-tokens"")
                .addHeader(""Authorization"", ""YELLOWFIN ts="" + System.currentTimeMillis() + "" , nonce="" + new Random().nextLong())
                .addHeader(""Accept"", ""application/vnd.yellowfin.api-v1+json"")
                .addHeader(""Content-Type"", ""application/json"")
                .bodyString(""{ \""userName\"": \""""+ username + ""\"",\""password\"": \""""+ password + ""\""}"", null)
                .execute().returnContent();

        JsonObject jsonObject = new JsonParser().parse(c.asString()).getAsJsonObject();
        JsonElement accessToken = jsonObject.getAsJsonObject(""_embedded"").getAsJsonObject(""accessToken"").get(""securityToken"");

        if (accessToken!=null) {
            System.out.println(""Access Token: "" + accessToken);
        } else {
            System.out.println(""Token not retrieved successfully"");
            System.exit(-1);
        }
        return accessToken.getAsString();

    }

}
Code Block
languagec#
titleC#
collapsetrue
using System.Net.Http.Headers;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace YellowfinAPIExamples
{
    public class ListGroupMembers
    {
        static async Task Main(string[] args)
        {
            Console.WriteLine(""List Group Member Components"");

            string host = ""http://localhost:8080/Yellowfin"";
            string restUsername = ""admin@yellowfin.com.au"";
            string restPassword = ""test"";
            string groupName = ""New Group"";

            string token = await GenerateToken(host, restUsername, restPassword);

            int groupId = await RetrieveGroupIpIdForGroupName(host, token, groupName);

            using (var httpClient = new HttpClient())
            {
                httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(""YELLOWFIN"", ""ts="" + DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() + "", nonce="" + new Random().NextInt64() + "", token="" + token);
                httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(""application/vnd.yellowfin.api-v1+json""));

                HttpResponseMessage response = await httpClient.GetAsync(host + ""/api/user-groups/"" + groupId + ""/members"");
                if (response.IsSuccessStatusCode)
                {
                    string responseBody = await response.Content.ReadAsStringAsync();
                    Console.WriteLine(responseBody);
                }
                else
                {
                    Console.WriteLine(""Failed to retrieve group members. Status code: "" + response.StatusCode);
                }
            }
        }

        static async Task<int> RetrieveGroupIpIdForGroupName(string host, string token, string groupName)
        {
            using (var httpClient = new HttpClient())
            {
                httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(""YELLOWFIN"", ""ts="" + DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() + "", nonce="" + new Random().NextInt64() + "", token="" + token);
                httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(""application/vnd.yellowfin.api-v1+json""));

                HttpResponseMessage response = await httpClient.GetAsync(host + ""/api/user-groups"");
                if (response.IsSuccessStatusCode)
                {
                    string responseBody = await response.Content.ReadAsStringAsync();
                    JObject jsonObject = JsonConvert.DeserializeObject<JObject>(responseBody);
                    JArray groups = (JArray)jsonObject[""items""];

                    foreach (var group in groups)
                    {
                        if (groupName == group[""shortDescription""].ToString())
                        {
                            return (int)group[""userGroupId""];
                        }
                    }

                    Console.WriteLine(""Group could not be found for name:"" + groupName);
                    Environment.Exit(-1);
                }
                else
                {
                    Console.WriteLine(""Failed to retrieve group list. Status code: "" + response.StatusCode);
                    Environment.Exit(-1);
                }
            }

            return -1; // Should not reach here due to Environment.Exit
        }

        static async Task<string> GenerateToken(string host, string restUsername, string restPassword)
        {
            using (var client = new HttpClient())
            {
                long nonce = new Random().NextInt64();

                var request = new HttpRequestMessage(HttpMethod.Post, host + ""/api/refresh-tokens"");
                request.Headers.Add(""Authorization"", ""YELLOWFIN ts="" + DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() + "", nonce="" + nonce);
                request.Headers.Add(""Accept"", ""application/vnd.yellowfin.api-v1+json"");
                request.Content = new StringContent(
                    JsonConvert.SerializeObject(new { userName = restUsername, password = restPassword }),
                    System.Text.Encoding.UTF8,
                    ""application/json""
                );

                HttpResponseMessage response = await client.SendAsync(request);
                string responseContent = await response.Content.ReadAsStringAsync();

                JObject jsonObject = JsonConvert.DeserializeObject<JObject>(responseContent);
                string accessToken = jsonObject[""_embedded""][""accessToken""][""securityToken""].ToString();

                if (!string.IsNullOrEmpty(accessToken))
                {
                    Console.WriteLine(""Access Token: "" + accessToken);
                    return accessToken;
                }
                else
                {
                    Console.WriteLine(""Token not retrieved successfully"");
                    Environment.Exit(-1);
                }
            }

            return null; // Should not reach here due to Environment.Exit
        }
    }
}
Code Block
titleGo
collapsetrue
package main

import (
	""bytes""
	""encoding/json""
	""fmt""
	""io/ioutil""
	""math/rand""
	""net/http""
	""time""
)

func main() {
	fmt.Println(""List Group Member Components"")

	host := ""http://localhost:8080/Yellowfin""
	restUsername := ""admin@yellowfin.com.au""
	restPassword := ""test""
	groupName := ""New Group""

	token, err := generateToken(host, restUsername, restPassword)
	if err != nil {
		fmt.Println(""Error generating token:"", err)
		return
	}

	groupId, err := retrieveGroupIpIdForGroupName(host, token, groupName)
	if err != nil {
		fmt.Println(""Error retrieving group ID:"", err)
		return
	}

	err = listGroupMembers(host, token, groupId)
	if err != nil {
		fmt.Println(""Error listing group members:"", err)
	}
}

func retrieveGroupIpIdForGroupName(host, token, groupName string) (int, error) {
	client := &http.Client{}
	nonce := rand.Int63()
	req, err := http.NewRequest(""GET"", fmt.Sprintf(""%s/api/user-groups"", host), nil)
	if err != nil {
		return 0, fmt.Errorf(""error creating request: %v"", err)
	}

	req.Header.Set(""Authorization"", fmt.Sprintf(""YELLOWFIN ts=%d, nonce=%d, token=%s"", time.Now().UnixMilli(), nonce, token))
	req.Header.Set(""Accept"", ""application/vnd.yellowfin.api-v1+json"")
	req.Header.Set(""Content-Type"", ""application/json"")

	resp, err := client.Do(req)
	if err != nil {
		return 0, fmt.Errorf(""error sending request: %v"", err)
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return 0, fmt.Errorf(""error reading response body: %v"", err)
	}

	var jsonResponse map[string]interface{}
	err = json.Unmarshal(body, &jsonResponse)
	if err != nil {
		return 0, fmt.Errorf(""error parsing JSON response: %v"", err)
	}

	items, ok := jsonResponse[""items""].([]interface{})
	if !ok {
		return 0, fmt.Errorf(""error parsing group list from response"")
	}

	for _, item := range items {
		group := item.(map[string]interface{})
		if group[""shortDescription""] == groupName {
			groupId, ok := group[""userGroupId""].(float64)
			if !ok {
				return 0, fmt.Errorf(""error parsing group ID from response"")
			}
			return int(groupId), nil
		}
	}

	fmt.Println(""Group could not be found for name:"", groupName)
	return 0, fmt.Errorf(""group not found"")
}

func listGroupMembers(host, token string, groupId int) error {
	client := &http.Client{}
	nonce := rand.Int63()
	req, err := http.NewRequest(""GET"", fmt.Sprintf(""%s/api/user-groups/%d/members"", host, groupId), nil)
	if err != nil {
		return fmt.Errorf(""error creating request: %v"", err)
	}

	req.Header.Set(""Authorization"", fmt.Sprintf(""YELLOWFIN ts=%d, nonce=%d, token=%s"", time.Now().UnixMilli(), nonce, token))
	req.Header.Set(""Accept"", ""application/vnd.yellowfin.api-v1+json"")
	req.Header.Set(""Content-Type"", ""application/json"")

	resp, err := client.Do(req)
	if err != nil {
		return fmt.Errorf(""error sending request: %v"", err)
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return fmt.Errorf(""error reading response body: %v"", err)
	}

	fmt.Println(string(body))
	return nil
}

func generateToken(host, restUsername, restPassword string) (string, error) {
	nonce := rand.Int63()
	requestBody, err := json.Marshal(map[string]string{
		""userName"": restUsername,
		""password"": restPassword,
	})
	if err != nil {
		return """", fmt.Errorf(""error marshaling request body: %v"", err)
	}

	client := &http.Client{}
	req, err := http.NewRequest(""POST"", fmt.Sprintf(""%s/api/refresh-tokens"", host), bytes.NewBuffer(requestBody))
	if err != nil {
		return """", fmt.Errorf(""error creating request: %v"", err)
	}

	req.Header.Set(""Authorization"", fmt.Sprintf(""YELLOWFIN ts=%d, nonce=%d"", time.Now().UnixMilli(), nonce))
	req.Header.Set(""Accept"", ""application/vnd.yellowfin.api-v1+json"")
	req.Header.Set(""Content-Type"", ""application/json"")

	resp, err := client.Do(req)
	if err != nil {
		return """", fmt.Errorf(""error sending request: %v"", err)
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return """", fmt.Errorf(""error reading response body: %v"", err)
	}

	var jsonResponse map[string]interface{}
	err = json.Unmarshal(body, &jsonResponse)
	if err != nil {
		return """", fmt.Errorf(""error parsing JSON response: %v"", err)
	}

	accessToken, ok := jsonResponse[""_embedded""].(map[string]interface{})[""accessToken""].(map[string]interface{})[""securityToken""].(string)
	if !ok {
		return """", fmt.Errorf(""token not retrieved successfully"")
	}

	fmt.Println(""Access Token:"", accessToken)
	return accessToken, nil
}
Code Block
languagejs
titleJavaScript
collapsetrue
const fetch = require(""node-fetch"");

async function main() {
    console.log(""List Group Member Components"");

    const host = ""http://localhost:8080/Yellowfin"";
    const restUsername = ""admin@yellowfin.com.au"";
    const restPassword = ""test"";
    const groupName = ""New Group"";

    const token = await generateToken(host, restUsername, restPassword);
    if (token === null) {
        console.error(""Failed to retrieve access token"");
        return;
    }

    try {
        const groupId = await retrieveGroupIpIdForGroupName(host, token, groupName);
        await listGroupMembers(host, token, groupId);
    } catch (error) {
        console.error(""Error:"", error.message);
    }
}

async function retrieveGroupIpIdForGroupName(host, token, groupName) {
    const nonce = Math.floor(Math.random() * Number.MAX_SAFE_INTEGER);
    const headers = {
        'Authorization': `YELLOWFIN ts=${Date.now()}, nonce=${nonce}, token=${token}`,
        'Accept': 'application/vnd.yellowfin.api-v1+json',
        'Content-Type': 'application/json'
    };

    try {
        const response = await fetch(`${host}/api/user-groups`, { method: 'GET', headers: headers });
        if (!response.ok) {
            throw new Error(`HTTP error! Status: ${response.status}`);
        }

        const jsonResponse = await response.json();
        const groups = jsonResponse.items;

        for (let group of groups) {
            if (group.shortDescription === groupName) {
                return group.userGroupId;
            }
        }

        console.log(`Group could not be found for name: ${groupName}`);
        process.exit(-1);
    } catch (error) {
        console.error(""Error:"", error.message);
        throw error;
    }
}

async function listGroupMembers(host, token, groupId) {
    const nonce = Math.floor(Math.random() * Number.MAX_SAFE_INTEGER);
    const headers = {
        'Authorization': `YELLOWFIN ts=${Date.now()}, nonce=${nonce}, token=${token}`,
        'Accept': 'application/vnd.yellowfin.api-v1+json',
        'Content-Type': 'application/json'
    };

    try {
        const response = await fetch(`${host}/api/user-groups/${groupId}/members`, { method: 'GET', headers: headers });
        if (!response.ok) {
            throw new Error(`HTTP error! Status: ${response.status}`);
        }

        const responseBody = await response.text();
        console.log(responseBody);
    } catch (error) {
        console.error(""Error:"", error.message);
    }
}

async function generateToken(host, restUsername, restPassword) {
    const nonce = Math.floor(Math.random() * Number.MAX_SAFE_INTEGER);
    const headers = {
        'Authorization': `YELLOWFIN ts=${Date.now()}, nonce=${nonce}`,
        'Accept': 'application/vnd.yellowfin.api-v1+json',
        'Content-Type': 'application/json'
    };

    const body = JSON.stringify({ userName: restUsername, password: restPassword });

    try {
        const response = await fetch(`${host}/api/refresh-tokens`, { method: 'POST', headers: headers, body: body });
        if (!response.ok) {
            throw new Error(`HTTP error! Status: ${response.status}`);
        }

        const jsonResponse = await response.json();
        const accessToken = jsonResponse._embedded.accessToken.securityToken;

        if (accessToken) {
            console.log(`Access Token: ${accessToken}`);
            return accessToken;
        } else {
            console.log(""Token not retrieved"");
        }
    } catch (error) {
        console.error(""Error:"", error.message);
    }

    return null;
}

main();
Code Block
languagephp
titlePHP
collapsetrue
<?php

function main() {
    echo ""List Group Member Components\n"";

    $host = ""http://localhost:8080/Yellowfin"";
    $restUsername = ""admin@yellowfin.com.au"";
    $restPassword = ""test"";
    $groupName = ""New Group"";

    try {
        $token = generateToken($host, $restUsername, $restPassword);
    } catch (Exception $e) {
        echo ""Error generating token: "" . $e->getMessage();
        return;
    }

    try {
        $groupId = retrieveGroupIpIdForGroupName($host, $token, $groupName);
    } catch (Exception $e) {
        echo ""Error retrieving group ID: "" . $e->getMessage();
        return;
    }

    $nonce = mt_rand();
    $headers = array(
        'Authorization: YELLOWFIN ts=' . intval(microtime(true) * 1000) . ', nonce=' . $nonce . ', token=' . $token,
        'Accept: application/vnd.yellowfin.api-v1+json',
        'Content-Type: application/json'
    );

    try {
        $response = httpRequest('GET', ""$host/api/user-groups/$groupId/members"", $headers);
        echo $response;
    } catch (Exception $e) {
        echo ""Error sending request: "" . $e->getMessage();
    }
}

function generateToken($host, $restUsername, $restPassword) {
    $nonce = mt_rand();

    $requestBody = json_encode(array(
        ""userName"" => $restUsername,
        ""password"" => $restPassword
    ));

    $headers = array(
        'Authorization: YELLOWFIN ts=' . intval(microtime(true) * 1000) . ', nonce=' . $nonce,
        'Accept: application/vnd.yellowfin.api-v1+json',
        'Content-Type: application/json'
    );

    $response = httpRequest('POST', ""$host/api/refresh-tokens"", $headers, $requestBody);

    $jsonResponse = json_decode($response, true);

    if (isset($jsonResponse[""_embedded""][""accessToken""][""securityToken""])) {
        $accessToken = $jsonResponse[""_embedded""][""accessToken""][""securityToken""];
        echo ""Access Token: "" . $accessToken . ""\n"";
        return $accessToken;
    } else {
        throw new Exception(""Token not retrieved successfully"");
    }
}

function retrieveGroupIpIdForGroupName($host, $token, $groupName) {
    $nonce = mt_rand();

    $headers = array(
        'Authorization: YELLOWFIN ts=' . intval(microtime(true) * 1000) . ', nonce=' . $nonce . ', token=' . $token,
        'Accept: application/vnd.yellowfin.api-v1+json',
        'Content-Type: application/json'
    );

    $response = httpRequest('GET', ""$host/api/user-groups"", $headers);

    $jsonResponse = json_decode($response, true);

    $groups = $jsonResponse[""items""];
    foreach ($groups as $group) {
        if ($group[""shortDescription""] === $groupName) {
            return $group[""userGroupId""];
        }
    }

    echo ""Group could not be found for name: $groupName\n"";
    exit(-1);
}

function httpRequest($method, $url, $headers, $data = null) {
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

    if ($data !== null) {
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    }

    $response = curl_exec($ch);

    if (curl_errno($ch)) {
        throw new Exception('Error: ' . curl_error($ch));
    }

    curl_close($ch);

    return $response;
}

main();

?>
Code Block
languagepy
titlePython
collapsetrue
import json
import random
import time
import requests

def main():
    print(""List Group Member Components"")

    host = ""http://localhost:8080/Yellowfin""
    rest_username = ""admin@yellowfin.com.au""
    rest_password = ""test""

    group_name = ""New Group""

    try:
        token = generate_token(host, rest_username, rest_password)
    except Exception as e:
        print(f""Error generating token: {e}"")
        return

    try:
        group_id = retrieve_group_ip_id_for_group_name(host, token, group_name)
    except Exception as e:
        print(f""Error retrieving group ID: {e}"")
        return

    nonce = random.randint(0, 2**63 - 1)
    headers = {
        'Authorization': f'YELLOWFIN ts={int(time.time() * 1000)}, nonce={nonce}, token={token}',
        'Accept': 'application/vnd.yellowfin.api-v1+json',
        'Content-Type': 'application/json'
    }

    try:
        response = requests.get(f""{host}/api/user-groups/{group_id}/members"", headers=headers)
        response.raise_for_status()
        print(response.text)
    except requests.RequestException as e:
        print(f""Error sending request: {e}"")

def generate_token(host, rest_username, rest_password):
    nonce = random.randint(0, 2**63 - 1)
    request_body = json.dumps({
        ""userName"": rest_username,
        ""password"": rest_password
    })
    headers = {
        'Authorization': f'YELLOWFIN ts={int(time.time() * 1000)}, nonce={nonce}',
        'Accept': 'application/vnd.yellowfin.api-v1+json',
        'Content-Type': 'application/json'
    }
    response = requests.post(f""{host}/api/refresh-tokens"", headers=headers, data=request_body)

    if response.status_code == 200:
        json_response = response.json()
        access_token = json_response[""_embedded""][""accessToken""][""securityToken""]
        print(""Access Token:"", access_token)
        return access_token
    else:
        raise Exception(""Token not retrieved successfully"")

def retrieve_group_ip_id_for_group_name(host, token, group_name):
    nonce = random.randint(0, 2**63 - 1)
    headers = {
        'Authorization': f'YELLOWFIN ts={int(time.time() * 1000)}, nonce={nonce}, token={token}',
        'Accept': 'application/vnd.yellowfin.api-v1+json',
        'Content-Type': 'application/json'
    }
    response = requests.get(f""{host}/api/user-groups"", headers=headers)

    if response.status_code == 200:
        json_response = response.json()
        groups = json_response[""items""]
        for group in groups:
            if group[""shortDescription""] == group_name:
                return group[""userGroupId""]
        print(f""Group could not be found for name: {group_name}"")
        exit(-1)
    else:
        raise Exception(""Error retrieving group"")

if __name__ == ""__main__"":
    main()

List Group Members (Flattened)

Members of existing groups can be returned using the GET /api/user-groups/{groupId}/flat-users end-point Get User Group Flat User List. This service will return the individual user members of a group. This service will return an expanded list of users that may have been included by group member components that represent multiple users, like other groups, roles or LDAP groups. 

The following example returns the JSON payload representing a list of group member components.

These code examples use Apache HTTP Client and GSON for handling REST calls and JSON serialization.

Code Block
languagejava
titleJava
collapsetrue
package rest.code.examples;
import java.io.IOException;
import java.util.Random;
import org.apache.hc.client5.http.fluent.Content;
import org.apache.hc.client5.http.fluent.Request;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
/**
 * List the flattened group members from a User Group using the Yellowfin REST API
 */
public class ListGroupMembersFlattened {
    public static void main(String[] args) throws Exception {

        System.out.println(""List Group Member Flattened"");

        String host = ""http://localhost:8080/Yellowfin"";
        String restUsername = ""admin@yellowfin.com.au"";
        String restPassword = ""test"";

        String groupName = ""New Group"";

        String token = generateToken(host, restUsername, restPassword);

        Integer groupId = retrieveGroupIpIdForGroupName(host, token, groupName);

        Content c = Request.get(host + ""/api/user-groups/"" + groupId + ""/flat-users"")
                .addHeader(""Authorization"", ""YELLOWFIN ts="" + System.currentTimeMillis() + "" , nonce="" + new Random().nextLong() + "", token="" + token)
                .addHeader(""Accept"", ""application/vnd.yellowfin.api-v1+json"")
                .addHeader(""Content-Type"", ""application/json"")
                .execute().returnContent();

        System.out.println(c.toString());

    }


    public static Integer retrieveGroupIpIdForGroupName(String host, String token, String groupName) throws IOException {

        Content c = Request.get(host + ""/api/user-groups"")
                .addHeader(""Authorization"", ""YELLOWFIN ts="" + System.currentTimeMillis() + "" , nonce="" + new Random().nextLong() + "", token="" + token)
                .addHeader(""Accept"", ""application/vnd.yellowfin.api-v1+json"")
                .addHeader(""Content-Type"", ""application/json"")
                .execute().returnContent();

        JsonObject jsonObject = new JsonParser().parse(c.asString()).getAsJsonObject();
        JsonElement groupList = jsonObject.get(""items"");
        JsonArray groups = groupList.getAsJsonArray();

        for (int i=0; i < groups.size(); i++ ) {
            JsonObject group = groups.getAsJsonArray().get(i).getAsJsonObject();
            if (groupName.equals(group.get(""shortDescription"").getAsString())) return group.get(""userGroupId"").getAsInt();
        }

        System.out.println(""Group could not be found for name:"" + groupName);
        System.exit(-1);

        return null;
    }

    /*
     *  This function generates an access token for a user that will grant them access to
     *  call REST API endpoints.
     */

    public static String generateToken(String host, String username, String password) throws IOException {

        Content c = Request.post(host + ""/api/refresh-tokens"")
                .addHeader(""Authorization"", ""YELLOWFIN ts="" + System.currentTimeMillis() + "" , nonce="" + new Random().nextLong())
                .addHeader(""Accept"", ""application/vnd.yellowfin.api-v1+json"")
                .addHeader(""Content-Type"", ""application/json"")
                .bodyString(""{ \""userName\"": \""""+ username + ""\"",\""password\"": \""""+ password + ""\""}"", null)
                .execute().returnContent();

        JsonObject jsonObject = new JsonParser().parse(c.asString()).getAsJsonObject();
        JsonElement accessToken = jsonObject.getAsJsonObject(""_embedded"").getAsJsonObject(""accessToken"").get(""securityToken"");

        if (accessToken!=null) {
            System.out.println(""Access Token: "" + accessToken);
        } else {
            System.out.println(""Token not retrieved successfully"");
            System.exit(-1);
        }
        return accessToken.getAsString();

    }

}
Code Block
languagec#
titleC#
collapsetrue
using System.Net.Http.Headers;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace YellowfinAPIExamples
{
    public class ListGroupMembersFlattened
    {
        static async Task Main(string[] args)
        {
            Console.WriteLine(""List Group Member Flattened"");

            string host = ""http://localhost:8080/Yellowfin"";
            string restUsername = ""admin@yellowfin.com.au"";
            string restPassword = ""test"";
            string groupName = ""New Group"";

            string token = await GenerateToken(host, restUsername, restPassword);

            int groupId = await RetrieveGroupIpIdForGroupName(host, token, groupName);

            using (var httpClient = new HttpClient())
            {
                httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(""YELLOWFIN"", 
                    $""ts={DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()}, nonce={new Random().NextInt64()}, token={token}"");
                httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(""application/vnd.yellowfin.api-v1+json""));

                HttpResponseMessage response = await httpClient.GetAsync($""{host}/api/user-groups/{groupId}/flat-users"");
                if (response.IsSuccessStatusCode)
                {
                    string responseBody = await response.Content.ReadAsStringAsync();
                    Console.WriteLine(responseBody);
                }
                else
                {
                    Console.WriteLine(""Failed to retrieve group members. Status code: "" + response.StatusCode);
                }
            }
        }

        static async Task<int> RetrieveGroupIpIdForGroupName(string host, string token, string groupName)
        {
            using (var httpClient = new HttpClient())
            {
                httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(""YELLOWFIN"", 
                    $""ts={DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()}, nonce={new Random().NextInt64()}, token={token}"");
                httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(""application/vnd.yellowfin.api-v1+json""));

                HttpResponseMessage response = await httpClient.GetAsync($""{host}/api/user-groups"");
                if (!response.IsSuccessStatusCode)
                {
                    throw new HttpRequestException($""Failed to retrieve user groups. Status code: {response.StatusCode}"");
                }

                string responseBody = await response.Content.ReadAsStringAsync();
                JObject jsonObject = JsonConvert.DeserializeObject<JObject>(responseBody);
                JArray groups = (JArray)jsonObject[""items""];

                foreach (var group in groups)
                {
                    if (group[""shortDescription""].ToString() == groupName)
                    {
                        return (int)group[""userGroupId""];
                    }
                }

                Console.WriteLine(""Group could not be found for name: "" + groupName);
                Environment.Exit(-1);
                return 0;
            }
        }

        static async Task<string> GenerateToken(string host, string username, string password)
        {
            using (var client = new HttpClient())
            {
                long nonce = new Random().NextInt64();

                var request = new HttpRequestMessage(HttpMethod.Post, $""{host}/api/refresh-tokens"")
                {
                    Content = new StringContent(
                        JsonConvert.SerializeObject(new { userName = username, password = password }),
                        System.Text.Encoding.UTF8,
                        ""application/json""
                    )
                };

                request.Headers.Authorization = new AuthenticationHeaderValue(""YELLOWFIN"", $""ts={DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()}, nonce={nonce}"");
                request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(""application/vnd.yellowfin.api-v1+json""));

                HttpResponseMessage response = await client.SendAsync(request);
                string responseContent = await response.Content.ReadAsStringAsync();

                JObject jsonObject = JsonConvert.DeserializeObject<JObject>(responseContent);
                string accessToken = jsonObject[""_embedded""][""accessToken""][""securityToken""].ToString();

                if (!string.IsNullOrEmpty(accessToken))
                {
                    Console.WriteLine(""Access Token: "" + accessToken);
                }
                else
                {
                    Console.WriteLine(""Token not retrieved successfully"");
                    Environment.Exit(-1);
                }

                return accessToken;
            }
        }
    }
}
Code Block
titleGo
collapsetrue
package main

import (
	""bytes""
	""encoding/json""
	""fmt""
	""io/ioutil""
	""math/rand""
	""net/http""
	""os""
	""time""
)

func main() {
	fmt.Println(""List Group Member Flattened"")

	host := ""http://localhost:8080/Yellowfin""
	restUsername := ""admin@yellowfin.com.au""
	restPassword := ""test""
	groupName := ""New Group""

	token, err := generateToken(host, restUsername, restPassword)
	if err != nil {
		fmt.Println(""Error generating token:"", err)
		return
	}

	groupId, err := retrieveGroupIpIdForGroupName(host, token, groupName)
	if err != nil {
		fmt.Println(""Error retrieving group ID:"", err)
		return
	}

	client := &http.Client{}
	req, err := http.NewRequest(""GET"", fmt.Sprintf(""%s/api/user-groups/%d/flat-users"", host, groupId), nil)
	if err != nil {
		fmt.Println(""Error creating request:"", err)
		return
	}

	nonce := rand.Int63()
	req.Header.Set(""Authorization"", fmt.Sprintf(""YELLOWFIN ts=%d, nonce=%d, token=%s"", time.Now().UnixMilli(), nonce, token))
	req.Header.Set(""Accept"", ""application/vnd.yellowfin.api-v1+json"")
	req.Header.Set(""Content-Type"", ""application/json"")

	resp, err := client.Do(req)
	if err != nil {
		fmt.Println(""Error sending request:"", err)
		return
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println(""Error reading response body:"", err)
		return
	}

	fmt.Println(string(body))
}

func retrieveGroupIpIdForGroupName(host, token, groupName string) (int, error) {
	client := &http.Client{}
	req, err := http.NewRequest(""GET"", fmt.Sprintf(""%s/api/user-groups"", host), nil)
	if err != nil {
		return 0, fmt.Errorf(""error creating request: %v"", err)
	}

	nonce := rand.Int63()
	req.Header.Set(""Authorization"", fmt.Sprintf(""YELLOWFIN ts=%d, nonce=%d, token=%s"", time.Now().UnixMilli(), nonce, token))
	req.Header.Set(""Accept"", ""application/vnd.yellowfin.api-v1+json"")
	req.Header.Set(""Content-Type"", ""application/json"")

	resp, err := client.Do(req)
	if err != nil {
		return 0, fmt.Errorf(""error sending request: %v"", err)
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return 0, fmt.Errorf(""error reading response body: %v"", err)
	}

	var jsonObject map[string]interface{}
	if err := json.Unmarshal(body, &jsonObject); err != nil {
		return 0, fmt.Errorf(""error parsing JSON response: %v"", err)
	}

	items, ok := jsonObject[""items""].([]interface{})
	if !ok {
		return 0, fmt.Errorf(""items not found in response"")
	}

	for _, item := range items {
		group := item.(map[string]interface{})
		if group[""shortDescription""] == groupName {
			return int(group[""userGroupId""].(float64)), nil
		}
	}

	fmt.Println(""Group could not be found for name:"", groupName)
	os.Exit(-1)
	return 0, fmt.Errorf(""group not found"")
}

func generateToken(host, username, password string) (string, error) {
	nonce := rand.Int63()
	requestBody, err := json.Marshal(map[string]string{
		""userName"": username,
		""password"": password,
	})
	if err != nil {
		return """", fmt.Errorf(""error marshaling request body: %v"", err)
	}

	client := &http.Client{}
	request, err := http.NewRequest(""POST"", fmt.Sprintf(""%s/api/refresh-tokens"", host), bytes.NewBuffer(requestBody))
	if err != nil {
		return """", fmt.Errorf(""error creating request: %v"", err)
	}

	request.Header.Set(""Authorization"", fmt.Sprintf(""YELLOWFIN ts=%d, nonce=%d"", time.Now().UnixMilli(), nonce))
	request.Header.Set(""Accept"", ""application/vnd.yellowfin.api-v1+json"")
	request.Header.Set(""Content-Type"", ""application/json"")

	response, err := client.Do(request)
	if err != nil {
		return """", fmt.Errorf(""error sending request: %v"", err)
	}
	defer response.Body.Close()

	responseBody, err := ioutil.ReadAll(response.Body)
	if err != nil {
		return """", fmt.Errorf(""error reading response body: %v"", err)
	}

	var jsonResponse map[string]interface{}
	if err := json.Unmarshal(responseBody, &jsonResponse); err != nil {
		return """", fmt.Errorf(""error parsing JSON response: %v"", err)
	}

	accessToken, ok := jsonResponse[""_embedded""].(map[string]interface{})[""accessToken""].(map[string]interface{})[""securityToken""].(string)
	if !ok {
		return """", fmt.Errorf(""token not retrieved successfully"")
	}

	fmt.Println(""Access Token:"", accessToken)
	return accessToken, nil
}
Code Block
languagejs
titleJavaScript
collapsetrue
const fetch = require('node-fetch');

async function main() {
    console.log(""List Group Member Flattened"");

    const host = ""http://localhost:8080/Yellowfin"";
    const restUsername = ""admin@yellowfin.com.au"";
    const restPassword = ""test"";
    const groupName = ""New Group"";

    const token = await generateToken(host, restUsername, restPassword);

    if (token === null) {
        console.error(""Failed to retrieve access token"");
        return;
    }

    const groupId = await retrieveGroupIpIdForGroupName(host, token, groupName);

    if (groupId === null) {
        console.error(""Failed to retrieve group ID"");
        return;
    }

    const nonce = Math.floor(Math.random() * Number.MAX_SAFE_INTEGER);
    const headers = {
        'Authorization': `YELLOWFIN ts=${Date.now()}, nonce=${nonce}, token=${token}`,
        'Accept': 'application/vnd.yellowfin.api-v1+json',
        'Content-Type': 'application/json'
    };

    try {
        const response = await fetch(`${host}/api/user-groups/${groupId}/flat-users`, {
            method: 'GET',
            headers: headers
        });

        if (!response.ok) {
            throw new Error(`HTTP error! Status: ${response.status}`);
        }

        const responseBody = await response.text();
        console.log(responseBody);
    } catch (error) {
        console.error(""Error:"", error.message);
    }
}

async function retrieveGroupIpIdForGroupName(host, token, groupName) {
    const nonce = Math.floor(Math.random() * Number.MAX_SAFE_INTEGER);
    const headers = {
        'Authorization': `YELLOWFIN ts=${Date.now()}, nonce=${nonce}, token=${token}`,
        'Accept': 'application/vnd.yellowfin.api-v1+json',
        'Content-Type': 'application/json'
    };

    try {
        const response = await fetch(`${host}/api/user-groups`, {
            method: 'GET',
            headers: headers
        });

        if (!response.ok) {
            throw new Error(`HTTP error! Status: ${response.status}`);
        }

        const jsonObject = await response.json();
        const groups = jsonObject.items;

        for (const group of groups) {
            if (group.shortDescription === groupName) {
                return group.userGroupId;
            }
        }

        console.error(""Group could not be found for name: "" + groupName);
        process.exit(-1);
    } catch (error) {
        console.error(""Error:"", error.message);
    }

    return null;
}

async function generateToken(host, username, password) {
    const nonce = Math.floor(Math.random() * Number.MAX_SAFE_INTEGER);
    const headers = {
        'Authorization': `YELLOWFIN ts=${Date.now()}, nonce=${nonce}`,
        'Accept': 'application/vnd.yellowfin.api-v1+json',
        'Content-Type': 'application/json'
    };

    const body = JSON.stringify({
        userName: username,
        password: password
    });

    try {
        const response = await fetch(`${host}/api/refresh-tokens`, {
            method: 'POST',
            headers: headers,
            body: body
        });

        if (!response.ok) {
            throw new Error(`HTTP error! Status: ${response.status}`);
        }

        const jsonResponse = await response.json();
        const accessToken = jsonResponse._embedded.accessToken.securityToken;

        if (accessToken) {
            console.log(`Access Token: ${accessToken}`);
        } else {
            console.error(""Token not retrieved successfully"");
            process.exit(-1);
        }

        return accessToken;
    } catch (error) {
        console.error(""Error:"", error.message);
    }

    return null;
}

main();
Code Block
languagephp
titlePHP
collapsetrue
<?php

function main() {
    echo ""List Group Member Flattened\n"";

    $host = ""http://localhost:8080/Yellowfin"";
    $restUsername = ""admin@yellowfin.com.au"";
    $restPassword = ""test"";

    $groupName = ""New Group"";

    try {
        $token = generateToken($host, $restUsername, $restPassword);
    } catch (Exception $e) {
        echo ""Error generating token: "" . $e->getMessage() . ""\n"";
        return;
    }

    try {
        $groupId = retrieveGroupIpIdForGroupName($host, $token, $groupName);
    } catch (Exception $e) {
        echo ""Error retrieving group ID: "" . $e->getMessage() . ""\n"";
        return;
    }

    $nonce = mt_rand();
    $headers = array(
        'Authorization: YELLOWFIN ts=' . intval(microtime(true) * 1000) . ', nonce=' . $nonce . ', token=' . $token,
        'Accept: application/vnd.yellowfin.api-v1+json',
        'Content-Type: application/json'
    );

    try {
        $response = httpRequest('GET', ""$host/api/user-groups/$groupId/flat-users"", $headers);
        echo $response;
    } catch (Exception $e) {
        echo ""Error sending request: "" . $e->getMessage() . ""\n"";
    }
}

function retrieveGroupIpIdForGroupName($host, $token, $groupName) {
    $nonce = mt_rand();
    $headers = array(
        'Authorization: YELLOWFIN ts=' . intval(microtime(true) * 1000) . ', nonce=' . $nonce . ', token=' . $token,
        'Accept: application/vnd.yellowfin.api-v1+json',
        'Content-Type: application/json'
    );

    $response = httpRequest('GET', ""$host/api/user-groups"", $headers);

    $jsonObject = json_decode($response, true);
    $groups = $jsonObject['items'];

    foreach ($groups as $group) {
        if ($group['shortDescription'] === $groupName) {
            return $group['userGroupId'];
        }
    }

    echo ""Group could not be found for name: "" . $groupName . ""\n"";
    exit(-1);
}

function generateToken($host, $username, $password) {
    $nonce = mt_rand();
    $headers = array(
        'Authorization: YELLOWFIN ts=' . intval(microtime(true) * 1000) . ', nonce=' . $nonce,
        'Accept: application/vnd.yellowfin.api-v1+json',
        'Content-Type: application/json'
    );

    $requestBody = json_encode(array(
        ""userName"" => $username,
        ""password"" => $password
    ));

    $response = httpRequest('POST', ""$host/api/refresh-tokens"", $headers, $requestBody);

    $jsonResponse = json_decode($response, true);
    if (isset($jsonResponse[""_embedded""][""accessToken""][""securityToken""])) {
        $accessToken = $jsonResponse[""_embedded""][""accessToken""][""securityToken""];
        echo ""Access Token: "" . $accessToken . ""\n"";
        return $accessToken;
    } else {
        throw new Exception(""Token not retrieved successfully"");
    }
}

function httpRequest($method, $url, $headers, $data = null) {
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

    if ($data !== null) {
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    }

    $response = curl_exec($ch);

    if (curl_errno($ch)) {
        throw new Exception('Error: ' . curl_error($ch));
    }

    curl_close($ch);

    return $response;
}

main();

?>
Code Block
languagepy
titlePython
collapsetrue
import json
import random
import time
import requests

def main():
    print(""List Group Member Flattened"")

    host = ""http://localhost:8080/Yellowfin""
    rest_username = ""admin@yellowfin.com.au""
    rest_password = ""test""

    group_name = ""New Group""

    try:
        token = generate_token(host, rest_username, rest_password)
    except Exception as e:
        print(f""Error generating token: {e}"")
        return

    try:
        group_id = retrieve_group_ip_id_for_group_name(host, token, group_name)
    except Exception as e:
        print(f""Error retrieving group ID: {e}"")
        return

    nonce = random.randint(0, 2**63 - 1)
    headers = {
        'Authorization': f'YELLOWFIN ts={int(time.time() * 1000)}, nonce={nonce}, token={token}',
        'Accept': 'application/vnd.yellowfin.api-v1+json',
        'Content-Type': 'application/json'
    }

    try:
        response = requests.get(f""{host}/api/user-groups/{group_id}/flat-users"", headers=headers)
        response.raise_for_status()
        print(response.text)
    except requests.RequestException as e:
        print(f""Error sending request: {e}"")

def retrieve_group_ip_id_for_group_name(host, token, group_name):
    nonce = random.randint(0, 2**63 - 1)
    headers = {
        'Authorization': f'YELLOWFIN ts={int(time.time() * 1000)}, nonce={nonce}, token={token}',
        'Accept': 'application/vnd.yellowfin.api-v1+json',
        'Content-Type': 'application/json'
    }

    response = requests.get(f""{host}/api/user-groups"", headers=headers)
    response.raise_for_status()

    json_object = response.json()
    groups = json_object['items']

    for group in groups:
        if group['shortDescription'] == group_name:
            return group['userGroupId']

    print(f""Group could not be found for name: {group_name}"")
    exit(-1)

def generate_token(host, rest_username, rest_password):
    nonce = random.randint(0, 2**63 - 1)
    headers = {
        'Authorization': f'YELLOWFIN ts={int(time.time() * 1000)}, nonce={nonce}',
        'Accept': 'application/vnd.yellowfin.api-v1+json',
        'Content-Type': 'application/json'
    }

    request_body = json.dumps({
        ""userName"": rest_username,
        ""password"": rest_password
    })

    response = requests.post(f""{host}/api/refresh-tokens"", headers=headers, data=request_body)
    response.raise_for_status()

    json_response = response.json()
    access_token = json_response[""_embedded""][""accessToken""][""securityToken""]
    print(""Access Token:"", access_token)

    return access_token

if __name__ == ""__main__"":
    main()