30日間の無料評価版をお試しいただけます。

Versions Compared

Key

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

...

Code Block
languagejava
themeEclipse
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.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
/**
 * Create a new Client Organization using the Yellowfin REST API
 */
public class CreateClientOrg {
    public static void main(String[] args) throws Exception {
 
        String host = "http://localhost:8080/Yellowfin";
        String restUsername = "admin@yellowfin.com.au";
        String restPassword = "test";
 
        String newTenantName = "New Client";
        String newTenantCode = "NEWCLIENT";
 
        String token = generateToken(host, restUsername, restPassword);
 
        String createTenantPayload =
                "{" +
                        "  \"clientRefId\": \"" + newTenantCode + "\"," +
                        "  \"name\": \"" + newTenantName + "\"," +
                        "  \"defaultTimezone\": \"AUSTRALIA/SYDNEY\"," +
                        "  \"customStylePath\": \"newClientStylePath\" " +
                        "}";
 
        System.out.println("Payload: " + createTenantPayload);
 
        Content c = Request.post(host + "/api/orgs")
                .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")
                .bodyString(createTenantPayload, null)
                .execute().returnContent();
 
        System.out.print(c.asString());
 
    }
 
 
 
    /*
     *  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#
themeEclipse
titleC#
collapsetrue
using System.Net.Http.Headers;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
 
namespace YellowfinAPIExamples
{
    public class CreateClientOrg
    {
        static async Task Main(string[] args)
        {
            string host = "http://localhost:8080/Yellowfin";
            string restUsername = "admin@yellowfin.com.au";
            string restPassword = "test";
 
            string newTenantName = "New Client";
            string newTenantCode = "NEWCLIENT";
 
            string token = await GenerateToken(host, restUsername, restPassword);
 
            string createTenantPayload = "{" +
                "  \"clientRefId\": \"" + newTenantCode + "\"," +
                "  \"name\": \"" + newTenantName + "\"," +
                "  \"defaultTimezone\": \"AUSTRALIA/SYDNEY\"," +
                "  \"customStylePath\": \"newClientStylePath\" " +
                "}";
 
            Console.WriteLine("Payload: " + createTenantPayload);
 
            long nonce = new Random().NextInt64();
 
            using (var httpClient = new HttpClient())
            {
                httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("YELLOWFIN", "ts=" + DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() + " , nonce=" + nonce + ", token=" + token);
                httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/vnd.yellowfin.api-v1+json"));
 
                var content = new StringContent(createTenantPayload, System.Text.Encoding.UTF8, "application/json");
 
                HttpResponseMessage response = await httpClient.PostAsync(host + "/api/orgs", content);
                if (response.IsSuccessStatusCode)
                {
                    string responseBody = await response.Content.ReadAsStringAsync();
                    Console.WriteLine(responseBody);
                }
                else
                {
                    Console.WriteLine("Failed to create client org. Status code: " + response.StatusCode);
                }
            }
        }
 
        static async Task<string> GenerateToken(string host, string username, string password)
        {
            using (var client = new HttpClient())
            {
                // Generate nonce
                long nonce = new Random().NextInt64();
 
                // Create HTTP request
                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 = username, password = password }),
                    System.Text.Encoding.UTF8,
                    "application/json"
                );
 
                // Send request and get response
                HttpResponseMessage response = await client.SendAsync(request);
                string responseContent = await response.Content.ReadAsStringAsync();
 
                // Parse JSON response
                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");
                    Environment.Exit(-1);
                }
 
                return accessToken;
            }
        }
    }
}
Code Block
themeEclipse
titleGo
collapsetrue
package main
 
import (
    "bytes"
    "encoding/json"
    "fmt"
    "io/ioutil"
    "math/rand"
    "net/http"
    "time"
)
 
func main() {
    host := "http://localhost:8080/Yellowfin"
    restUsername := "admin@yellowfin.com.au"
    restPassword := "test"
 
    newTenantName := "New Client"
    newTenantCode := "NEWCLIENT"
 
    token, err := generateToken(host, restUsername, restPassword)
    if err != nil {
        fmt.Println("Error generating token:", err)
        return
    }
 
    fmt.Println("Payload:", createTenantPayload(newTenantCode, newTenantName))
 
    client := &http.Client{}
    reqBody := createTenantPayload(newTenantCode, newTenantName)
    req, err := http.NewRequest("POST", host+"/api/orgs", bytes.NewBuffer(reqBody))
    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 generateToken(host, restUsername, restPassword string) (string, error) {
    // Generate nonce
    nonce := rand.Int63()
 
    // Create request body
    requestBody, err := json.Marshal(map[string]string{
        "userName": restUsername,
        "password": restPassword,
    })
    if err != nil {
        fmt.Println("Error marshaling request body:", err)
        return "", err
    }
 
    // Create HTTP client
    client := &http.Client{}
 
    // Create HTTP request
    request, err := http.NewRequest("POST", host+"/api/refresh-tokens", bytes.NewBuffer(requestBody))
    if err != nil {
        fmt.Println("Error creating request:", err)
        return "", err
    }
 
    // Add request headers
    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")
 
    // Send HTTP request
    response, err := client.Do(request)
    if err != nil {
        fmt.Println("Error sending request:", err)
        return "", err
    }
    defer response.Body.Close()
 
    // Read response body
    responseBody, err := ioutil.ReadAll(response.Body)
    if err != nil {
        fmt.Println("Error reading response body:", err)
        return "", err
    }
 
    // Parse JSON response
    var jsonResponse map[string]interface{}
    err = json.Unmarshal(responseBody, &jsonResponse)
    if err != nil {
        fmt.Println("Error parsing JSON response:", err)
        return "", err
    }
 
    // Get access token from response
    accessToken, ok := jsonResponse["_embedded"].(map[string]interface{})["accessToken"].(map[string]interface{})["securityToken"].(string)
    if !ok {
        fmt.Println("Token not retrieved")
        return "", fmt.Errorf("Token not retrieved successfully")
    }
 
    return accessToken, nil
}
 
func createTenantPayload(newTenantCode, newTenantName string) []byte {
    payload := fmt.Sprintf("{\"clientRefId\": \"%s\", \"name\": \"%s\", \"defaultTimezone\": \"AUSTRALIA/SYDNEY\", \"customStylePath\": \"newClientStylePath\" }", newTenantCode, newTenantName)
    return []byte(payload)
}

...

Code Block
languagejava
themeEclipse
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.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
/**
 * List Client Organizations using the Yellowfin REST API
 */
public class ListClientOrgs {
    public static void main(String[] args) throws Exception {
 
        String host = "http://localhost:8080/Yellowfin";
        String restUsername = "admin@yellowfin.com.au";
        String restPassword = "test";
 
        String token = generateToken(host, restUsername, restPassword);
 
        Content c = Request.get(host + "/api/orgs")
                .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.print(c.asString());
 
    }
 
 
    /*
     *  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
themeEclipse
titleGo
collapsetrue
package main
 
import (
    "bytes"
    "encoding/json"
    "fmt"
    "io/ioutil"
    "math/rand"
    "net/http"
    "time"
)
 
func main() {
    host := "http://localhost:8080/Yellowfin"
    restUsername := "admin@yellowfin.com.au"
    restPassword := "test"
 
    token, err := generateToken(host, restUsername, restPassword)
    if err != nil {
        fmt.Println("Error generating token:", err)
        return
    }
 
    client := &http.Client{}
    req, err := http.NewRequest("GET", host+"/api/orgs", 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 generateToken(host, restUsername, restPassword string) (string, error) {
    nonce := rand.Int63()
 
    requestBody, err := json.Marshal(map[string]string{
        "userName": restUsername,
        "password": restPassword,
    })
    if err != nil {
        fmt.Println("Error marshaling request body:", err)
        return "", err
    }
 
    client := &http.Client{}
    request, err := http.NewRequest("POST", host+"/api/refresh-tokens", bytes.NewBuffer(requestBody))
    if err != nil {
        fmt.Println("Error creating request:", err)
        return "", 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 {
        fmt.Println("Error sending request:", err)
        return "", err
    }
    defer response.Body.Close()
 
    responseBody, err := ioutil.ReadAll(response.Body)
    if err != nil {
        fmt.Println("Error reading response body:", err)
        return "", err
    }
 
    var jsonResponse map[string]interface{}
    err = json.Unmarshal(responseBody, &jsonResponse)
    if err != nil {
        fmt.Println("Error parsing JSON response:", err)
        return "", err
    }
 
    accessToken, ok := jsonResponse["_embedded"].(map[string]interface{})["accessToken"].(map[string]interface{})["securityToken"].(string)
    if !ok {
        fmt.Println("Token not retrieved")
        return "", fmt.Errorf("Token not retrieved successfully")
    }
 
    fmt.Println("Access Token:", accessToken)
    return accessToken, nil
}

...

Code Block
languagejava
themeEclipse
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;
/**
 * Add a User access to a Tenant using the Yellowfin REST API
 */
public class AddUserToClientOrg {
    public static void main(String[] args) throws Exception {
 
        System.out.print("Add a User to a Tenant");
 
        String host = "http://localhost:8080/Yellowfin";
        String restUsername = "admin@yellowfin.com.au";
        String restPassword = "test";
 
        String usernameOfUserToAddtoTenant = "user1@yellowfin.com.au";
        String tenantClientReferenceId = "NEWCLIENT";
 
        String token = generateToken(host, restUsername, restPassword);
 
        Integer tenantId = retrieveTenantIpIdForTenantName(host, token, tenantClientReferenceId);
        Integer userIpId = retrieveUserIpIdForUsername(host, token, usernameOfUserToAddtoTenant);
 
        String addUserToClientPayload = " { \"userId\": " + userIpId + " }";
 
        System.out.println("Tenant Id: " + tenantId);
        System.out.println("User IpId: " + userIpId);
        System.out.println("PayLoad: " + addUserToClientPayload);
 
        Content c = Request.post(host + "/api/orgs/" + tenantId + "/user-access")
                .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")
                .bodyString(addUserToClientPayload, null)
                .execute().returnContent();
 
        System.out.print(c.asString());
 
    }
    /*
     *  This function fetches a user's integer id for a given username
     */
 
    public static Integer retrieveUserIpIdForUsername(String host, String token, String userName) throws IOException {
 
        Content c = Request.get(host + "/api/rpc/users/user-details-by-username/" + userName)
                .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 userIpJsonAttribute = jsonObject.get("userId");
        Integer userIpId = userIpJsonAttribute.getAsInt();
 
        return userIpId;
 
    }
 
    /*
     *  This function fetches a client organization's integer id for a given clientRefCode
     */
 
    public static Integer retrieveTenantIpIdForTenantName(String host, String token, String tenantCode) throws IOException {
 
        Content c = Request.get(host + "/api/orgs")
                .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 tenantList = jsonObject.get("items");
        JsonArray tenants = tenantList.getAsJsonArray();
 
        for (int i=0; i < tenants.size(); i++ ) {
            JsonObject tenant = tenants.getAsJsonArray().get(i).getAsJsonObject();
            if (!tenant.has("clientRefId")) continue;
            if (tenantCode.equals(tenant.get("clientRefId").getAsString())) return tenant.get("ipOrg").getAsInt();
        }
 
        System.out.println("Tenant could not be found for code:" + tenantCode);
        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
themeEclipse
titleGo
collapsetrue
package main
 
import (
    "bytes"
    "encoding/json"
    "fmt"
    "io/ioutil"
    "math/rand"
    "net/http"
    "os"
    "time"
)
 
func main() {
    fmt.Println("Add a User to a Tenant")
 
    host := "http://localhost:8080/Yellowfin"
    restUsername := "admin@yellowfin.com.au"
    restPassword := "test"
 
    usernameOfUserToAddToTenant := "user1@yellowfin.com.au"
    tenantClientReferenceId := "NEWCLIENT"
 
    token, err := generateToken(host, restUsername, restPassword)
    if err != nil {
        fmt.Println("Error generating token:", err)
        return
    }
 
    tenantId, err := retrieveTenantIpIdForTenantName(host, token, tenantClientReferenceId)
    if err != nil {
        fmt.Println("Error retrieving tenant ID:", err)
        return
    }
 
    userIpId, err := retrieveUserIpIdForUsername(host, token, usernameOfUserToAddToTenant)
    if err != nil {
        fmt.Println("Error retrieving user ID:", err)
        return
    }
 
    addUserToClientPayload := fmt.Sprintf(`{ "userId": %d }`, userIpId)
 
    fmt.Println("Tenant Id:", tenantId)
    fmt.Println("User IpId:", userIpId)
    fmt.Println("PayLoad:", addUserToClientPayload)
 
    client := &http.Client{}
    req, err := http.NewRequest("POST", fmt.Sprintf("%s/api/orgs/%d/user-access", host, tenantId), bytes.NewBuffer([]byte(addUserToClientPayload)))
    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 retrieveUserIpIdForUsername(host, token, userName string) (int, error) {
    client := &http.Client{}
    req, err := http.NewRequest("GET", fmt.Sprintf("%s/api/rpc/users/user-details-by-username/%s", host, userName), nil)
    if err != nil {
        return 0, 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, err
    }
    defer resp.Body.Close()
 
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        return 0, err
    }
 
    var jsonResponse map[string]interface{}
    err = json.Unmarshal(body, &jsonResponse)
    if err != nil {
        return 0, err
    }
 
    userIpId, ok := jsonResponse["userId"].(float64)
    if !ok {
        return 0, fmt.Errorf("User ID not found in response")
    }
 
    return int(userIpId), nil
}
 
func retrieveTenantIpIdForTenantName(host, token, tenantCode string) (int, error) {
    client := &http.Client{}
    req, err := http.NewRequest("GET", fmt.Sprintf("%s/api/orgs", host), nil)
    if err != nil {
        return 0, 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, err
    }
    defer resp.Body.Close()
 
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        return 0, err
    }
 
    var jsonResponse map[string]interface{}
    err = json.Unmarshal(body, &jsonResponse)
    if err != nil {
        return 0, err
    }
 
    tenants, ok := jsonResponse["items"].([]interface{})
    if !ok {
        return 0, fmt.Errorf("Tenant list not found in response")
    }
 
    for _, tenant := range tenants {
        tenantMap, ok := tenant.(map[string]interface{})
        if !ok {
            continue
        }
        clientRefId, ok := tenantMap["clientRefId"].(string)
        if ok && clientRefId == tenantCode {
            ipOrg, ok := tenantMap["ipOrg"].(float64)
            if ok {
                return int(ipOrg), nil
            }
        }
    }
 
    fmt.Println("Tenant could not be found for code:", tenantCode)
    os.Exit(-1)
    return 0, nil
}
 
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 "", err
    }
 
    client := &http.Client{}
    req, err := http.NewRequest("POST", fmt.Sprintf("%s/api/refresh-tokens", host), bytes.NewBuffer(requestBody))
    if err != nil {
        return "", 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 "", err
    }
    defer resp.Body.Close()
 
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        return "", err
    }
 
    var jsonResponse map[string]interface{}
    err = json.Unmarshal(body, &jsonResponse)
    if err != nil {
        return "", err
    }
 
    accessToken, ok := jsonResponse["_embedded"].(map[string]interface{})["accessToken"].(map[string]interface{})["securityToken"].(string)
    if !ok {
        return "", fmt.Errorf("Token not retrieved successfully")
    }
 
    return accessToken, nil
}

...

Code Block
languagejava
themeEclipse
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;
/**
 * Add a User access to a Tenant using the Yellowfin REST API
 */
public class RemoveUserFromClientOrg {
    public static void main(String[] args) throws Exception {
 
        System.out.print("Revoke Access to Tenant for User");
 
        String host = "http://localhost:8080/Yellowfin";
        String restUsername = "admin@yellowfin.com.au";
        String restPassword = "test";
 
        String usernameOfUserToRemoveFromTenant = "user1@yellowfin.com.au";
        String tenantClientReferenceId = "NEWCLIENT";
 
        String token = generateToken(host, restUsername, restPassword);
 
        Integer tenantId = retrieveTenantIpIdForTenantName(host, token, tenantClientReferenceId);
        Integer userIpId = retrieveUserIpIdForUsername(host, token, usernameOfUserToRemoveFromTenant);
 
 
        System.out.println("Tenant Id: " + tenantId);
        System.out.println("User IpId: " + userIpId);
 
        Content c = Request.delete(host + "/api/orgs/" + tenantId + "/user-access/" + userIpId)
                .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.print(c.asString());
 
    }
    /*
     *  This function fetches a user's integer id for a given username
     */
 
    public static Integer retrieveUserIpIdForUsername(String host, String token, String userName) throws IOException {
 
        Content c = Request.get(host + "/api/rpc/users/user-details-by-username/" + userName)
                .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 userIpJsonAttribute = jsonObject.get("userId");
        Integer userIpId = userIpJsonAttribute.getAsInt();
 
        return userIpId;
 
    }
 
    /*
     *  This function fetches a client organization's integer id for a given clientRefCode
     */
 
    public static Integer retrieveTenantIpIdForTenantName(String host, String token, String tenantCode) throws IOException {
 
        Content c = Request.get(host + "/api/orgs")
                .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 (!group.has("clientRefId")) continue;
            if (tenantCode.equals(group.get("clientRefId").getAsString())) return group.get("ipOrg").getAsInt();
        }
 
        System.out.println("Tenant could not be found for code:" + tenantCode);
        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
themeEclipse
titleGo
collapsetrue
package main
 
import (
    "bytes"
    "encoding/json"
    "fmt"
    "io/ioutil"
    "math/rand"
    "net/http"
    "time"
)
 
func main() {
    host := "http://localhost:8080/Yellowfin"
    restUsername := "admin@yellowfin.com.au"
    restPassword := "test"
    usernameOfUserToRemoveFromTenant := "user1@yellowfin.com.au"
    tenantClientReferenceId := "NEWCLIENT"
 
    token, err := generateToken(host, restUsername, restPassword)
    if err != nil {
        fmt.Println("Error generating token:", err)
        return
    }
 
    tenantId, err := retrieveTenantIpIdForTenantName(host, token, tenantClientReferenceId)
    if err != nil {
        fmt.Println("Error retrieving tenant ID:", err)
        return
    }
 
    userIpId, err := retrieveUserIpIdForUsername(host, token, usernameOfUserToRemoveFromTenant)
    if err != nil {
        fmt.Println("Error retrieving user IP ID:", err)
        return
    }
 
    fmt.Println("Tenant Id:", tenantId)
    fmt.Println("User IpId:", userIpId)
 
    client := &http.Client{}
    req, err := http.NewRequest("DELETE", fmt.Sprintf("%s/api/orgs/%d/user-access/%d", host, tenantId, userIpId), 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().UnixNano()/int64(time.Millisecond), 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 retrieveUserIpIdForUsername(host, token, userName string) (int, error) {
    client := &http.Client{}
    req, err := http.NewRequest("GET", host+"/api/rpc/users/user-details-by-username/"+userName, nil)
    if err != nil {
        return 0, err
    }
 
    nonce := rand.Int63()
 
    req.Header.Set("Authorization", fmt.Sprintf("YELLOWFIN ts=%d, nonce=%d, token=%s", time.Now().UnixNano()/int64(time.Millisecond), 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, err
    }
    defer resp.Body.Close()
 
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        return 0, err
    }
 
    var jsonResponse map[string]interface{}
    err = json.Unmarshal(body, &jsonResponse)
    if err != nil {
        return 0, err
    }
 
    userIpId := int(jsonResponse["userId"].(float64))
    return userIpId, nil
}
 
func retrieveTenantIpIdForTenantName(host, token, tenantCode string) (int, error) {
    client := &http.Client{}
    req, err := http.NewRequest("GET", host+"/api/orgs", nil)
    if err != nil {
        return 0, err
    }
 
    nonce := rand.Int63()
 
    req.Header.Set("Authorization", fmt.Sprintf("YELLOWFIN ts=%d, nonce=%d, token=%s", time.Now().UnixNano()/int64(time.Millisecond), 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, err
    }
    defer resp.Body.Close()
 
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        return 0, err
    }
 
    var jsonResponse map[string]interface{}
    err = json.Unmarshal(body, &jsonResponse)
    if err != nil {
        return 0, err
    }
 
    items := jsonResponse["items"].([]interface{})
    for _, item := range items {
        group := item.(map[string]interface{})
        if group["clientRefId"] != nil && group["clientRefId"].(string) == tenantCode {
            return int(group["ipOrg"].(float64)), nil
        }
    }
 
    return 0, fmt.Errorf("Tenant could not be found for code: %s", tenantCode)
}
 
func generateToken(host, username, password string) (string, error) {
    client := &http.Client{}
 
    nonce := rand.Int63()
 
    requestBody, err := json.Marshal(map[string]string{
        "userName": username,
        "password": password,
    })
    if err != nil {
        return "", err
    }
 
    req, err := http.NewRequest("POST", host+"/api/refresh-tokens", bytes.NewBuffer(requestBody))
    if err != nil {
        return "", err
    }
 
    req.Header.Set("Authorization", fmt.Sprintf("YELLOWFIN ts=%d, nonce=%d", time.Now().UnixNano()/int64(time.Millisecond), 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 "", err
    }
    defer resp.Body.Close()
 
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        return "", err
    }
 
    var jsonResponse map[string]interface{}
    err = json.Unmarshal(body, &jsonResponse)
    if err != nil {
        return "", err
    }
 
    accessToken := jsonResponse["_embedded"].(map[string]interface{})["accessToken"].(map[string]interface{})["securityToken"].(string)
    if accessToken == " {
        return "", fmt.Errorf("Token not retrieved successfully")
    }
 
    fmt.Println("Access Token:", accessToken)
    return accessToken, nil
}

...

Code Block
languagejava
themeEclipse
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 Users who have access to a Tenant using the Yellowfin REST API
*/
public class ListUserAccessToClientOrg {
   public static void main(String[] args) throws Exception {
      
        System.out.print("List Users who have Access to Tenant");
     
            String host = "http://localhost/yellowfinHead";
            String restUsername = "admin@yellowfin.com.au";
            String restPassword = "test";
             
            String tenantClientReferenceId = "NEWCLIENT";
             
            String token = generateToken(host, restUsername, restPassword);
                 
            Integer tenantId = retrieveTenantIpIdForTenantName(host, token, tenantClientReferenceId);
            System.out.println("Tenant Id: " + tenantId);
             
            Content c = Request.get(host + "/api/orgs/" + tenantId + "/user-access")
                    .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 userList = jsonObject.get("items");
        JsonArray users = userList.getAsJsonArray();
        
        System.out.println(users.size() + " user(s) have access to tenant " + tenantClientReferenceId);
        
        for (int i=0; i < users.size(); i++ ) {
                JsonObject user = users.getAsJsonArray().get(i).getAsJsonObject();
                System.out.println("User " + user.get("userId").getAsInt() + ": " + user.get("name").getAsString());
        }
        
   }
   /*
    *  This function fetches a client organization's integer id for a given clientRefCode
    */
   
   public static Integer retrieveTenantIpIdForTenantName(String host, String token, String tenantCode) throws IOException {
     
        Content c = Request.get(host + "/api/orgs")
                .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 (!group.has("clientRefId")) continue;
                if (tenantCode.equals(group.get("clientRefId").getAsString())) return group.get("ipOrg").getAsInt();
        }
        
       System.out.println("Tenant could not be found for code:" + tenantCode);
       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
themeEclipse
titleGo
collapsetrue
package main
 
import (
    "bytes"
    "encoding/json"
    "fmt"
    "io/ioutil"
    "math/rand"
    "net/http"
    "time"
)
 
func main() {
    host := "http://localhost:8080/Yellowfin"
    restUsername := "admin@yellowfin.com.au"
    restPassword := "test"
    tenantClientReferenceId := "NEWCLIENT"
 
    token, err := generateToken(host, restUsername, restPassword)
    if err != nil {
        fmt.Println("Error generating token:", err)
        return
    }
 
    tenantId, err := retrieveTenantIpIdForTenantName(host, token, tenantClientReferenceId)
    if err != nil {
        fmt.Println("Error retrieving tenant ID:", err)
        return
    }
    fmt.Println("Tenant ID:", tenantId)
 
    client := &http.Client{}
    req, err := http.NewRequest("GET", fmt.Sprintf("%s/api/orgs/%d/user-access", host, tenantId), 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
    }
 
    var response map[string]interface{}
    err = json.Unmarshal(body, &response)
    if err != nil {
        fmt.Println("Error parsing JSON:", err)
        return
    }
 
    userList := response["items"].([]interface{})
    fmt.Printf("%d user(s) have access to tenant %s\n", len(userList), tenantClientReferenceId)
 
    for _, u := range userList {
        user := u.(map[string]interface{})
        fmt.Printf("User %d: %s\n", int(user["userId"].(float64)), user["name"].(string))
    }
}
 
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 "", err
    }
 
    client := &http.Client{}
    req, err := http.NewRequest("POST", host+"/api/refresh-tokens", bytes.NewBuffer(requestBody))
    if err != nil {
        return "", 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 "", err
    }
    defer resp.Body.Close()
 
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        return "", err
    }
 
    var response map[string]interface{}
    err = json.Unmarshal(body, &response)
    if err != nil {
        return "", err
    }
 
    accessToken := response["_embedded"].(map[string]interface{})["accessToken"].(map[string]interface{})["securityToken"].(string)
    if accessToken == "" {
        return "", fmt.Errorf("Token not retrieved successfully")
    }
 
    return accessToken, nil
}
 
func retrieveTenantIpIdForTenantName(host, token, tenantCode string) (int, error) {
    nonce := rand.Int63()
 
    client := &http.Client{}
    req, err := http.NewRequest("GET", host+"/api/orgs", nil)
    if err != nil {
        return 0, 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, err
    }
    defer resp.Body.Close()
 
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        return 0, err
    }
 
    var response map[string]interface{}
    err = json.Unmarshal(body, &response)
    if err != nil {
        return 0, err
    }
 
    groups := response["items"].([]interface{})
    for _, g := range groups {
        group := g.(map[string]interface{})
 
        if group["clientRefId"] != nil {
            if group["clientRefId"].(string) == tenantCode {
                return int(group["ipOrg"].(float64)), nil
            }
        }
    }
 
    return 0, fmt.Errorf("Tenant could not be found for code: %s", tenantCode)
}

...

Code Block
languagejava
themeEclipse
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;
/**
 * Delete a Client Org using the Yellowfin REST API
 */
public class DeleteClientOrg {
    public static void main(String[] args) throws Exception {
 
        System.out.print("Delete a Tenant");
 
        String host = "http://localhost:8080/Yellowfin";
        String restUsername = "admin@yellowfin.com.au";
        String restPassword = "test";
 
        String tenantClientReferenceId = "NEWCLIENT";
 
        String token = generateToken(host, restUsername, restPassword);
 
        Integer tenantId = retrieveTenantIpIdForTenantName(host, token, tenantClientReferenceId);
 
        System.out.println("Tenant Id: " + tenantId);
 
        Content c = Request.delete(host + "/api/orgs/" + tenantId)
                .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.print(c.asString());
 
    }
 
    /*
     *  This function fetches a client organization's integer id for a given clientRefCode
     */
 
    public static Integer retrieveTenantIpIdForTenantName(String host, String token, String tenantCode) throws IOException {
 
        Content c = Request.get(host + "/api/orgs")
                .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 (!group.has("clientRefId")) continue;
            if (tenantCode.equals(group.get("clientRefId").getAsString())) return group.get("ipOrg").getAsInt();
        }
 
        System.out.println("Tenant could not be found for code:" + tenantCode);
        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
themeEclipse
titleGo
collapsetrue
package main
 
import (
    "bytes"
    "encoding/json"
    "fmt"
    "io/ioutil"
    "math/rand"
    "net/http"
    "time"
)
 
func main() {
    host := "http://localhost:8080/Yellowfin"
    restUsername := "admin@yellowfin.com.au"
    restPassword := "test"
    tenantClientReferenceId := "NEWCLIENT"
 
    token, err := generateToken(host, restUsername, restPassword)
    if err != nil {
        fmt.Println("Error generating token:", err)
        return
    }
 
    tenantId, err := retrieveTenantIpIdForTenantName(host, token, tenantClientReferenceId)
    if err != nil {
        fmt.Println("Error retrieving tenant ID:", err)
        return
    }
 
    fmt.Println("Tenant Id:", tenantId)
 
    client := &http.Client{}
    req, err := http.NewRequest("DELETE", fmt.Sprintf("%s/api/orgs/%d", host, tenantId), 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 retrieveTenantIpIdForTenantName(host, token, tenantCode string) (int, error) {
    client := &http.Client{}
    req, err := http.NewRequest("GET", fmt.Sprintf("%s/api/orgs", 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 jsonResponse map[string]interface{}
    if err := json.Unmarshal(body, &jsonResponse); err != nil {
        return 0, fmt.Errorf("error parsing JSON response: %v", err)
    }
 
    groups := jsonResponse["items"].([]interface{})
    for _, group := range groups {
        groupObj := group.(map[string]interface{})
        if clientRefId, ok := groupObj["clientRefId"].(string); ok && clientRefId == tenantCode {
            ipOrg := int(groupObj["ipOrg"].(float64))
            return ipOrg, nil
        }
    }
 
    return 0, fmt.Errorf("tenant could not be found for code: %s", tenantCode)
}
 
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{}
    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{}
    if err := json.Unmarshal(body, &jsonResponse); err != nil {
        return "", fmt.Errorf("error parsing JSON response: %v", err)
    }
 
    accessToken := jsonResponse["_embedded"].(map[string]interface{})["accessToken"].(map[string]interface{})["securityToken"].(string)
    if accessToken == "" {
        return "", fmt.Errorf("token not retrieved successfully")
    }
 
    fmt.Println("Access Token:", accessToken)
    return accessToken, nil
}

...