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

Versions Compared

Key

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

...

Code Block
titleGo
collapsetrue
package main

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

func main() {
        host := "http://localhost:8080/yellowfinHead"
            restUsername := "admin@yellowfin.com.au"
            restPassword := "test"

            // 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
        }

        // 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
        }

        // 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
        }
        defer response.Body.Close()

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

        // Parse JSON response
        var jsonResponse map[string]interface{}
        err = json.Unmarshal(responseBody, &jsonResponse)
        if err != nil {
                fmt.Println("Error parsing JSON response:", err)
                return
        }

        // 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.Println("Access Token:", accessToken)
}
Code Block
languagejs
titleJavaScript
collapsetrue
const fetch = require('node-fetch');

async function main() {
    const host = "http://localhost:8080/yellowfinHead";
    const restUsername = "admin@yellowfin.com.au";
    const restPassword = "test";

    // Generate nonce
    const nonce = Math.floor(Math.random() * Number.MAX_SAFE_INTEGER);

    // Create request headers
    const headers = {
        'Authorization': `YELLOWFIN ts=${Date.now()}, nonce=${nonce}`,
        'Accept': 'application/vnd.yellowfin.api-v1+json',
        'Content-Type': 'application/json'
    };

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

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

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

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

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

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

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

    // Generate nonce
    $nonce = mt_rand();

    // Create request body
    $requestBody = json_encode(array(
            "userName" => $restUsername,
            "password" => $restPassword
    ));

    // Create request headers
    $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);

    // Parse JSON response
    $jsonResponse = json_decode($response, true);

    // Get access token from response
    if (isset($jsonResponse["_embedded"]["accessToken"]["securityToken"])) {
        $accessToken = $jsonResponse["_embedded"]["accessToken"]["securityToken"];
        echo "Access Token: " . $accessToken;
    } else {
        echo "Token not retrieved";
    }
}

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

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

# Generate nonce
nonce = random.randint(0, 2**63 - 1)

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

# Create request headers
headers = {
    'Authorization': f'YELLOWFIN ts={int(time.time() * 1000)}, nonce={nonce}',
    'Accept': 'application/vnd.yellowfin.api-v1+json',
    'Content-Type': 'application/json'
}

# Send HTTP request
response = requests.post(host + "/api/refresh-tokens", headers=headers, data=request_body)

# Check response status
if response.status_code == 200:
    # Parse JSON response
    json_response = response.json()
    access_token = json_response["_embedded"]["accessToken"]["securityToken"]
    print("Access Token:", access_token)
else:
    print("Token not retrieved")

...