Page History
...
Code Block | ||||||
---|---|---|---|---|---|---|
| ||||||
package rest.code.examples; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Random; import org.apache.hc.client5.http.entity.mime.HttpMultipartMode; import org.apache.hc.client5.http.entity.mime.MultipartEntityBuilder; import org.apache.hc.client5.http.fluent.Content; import org.apache.hc.client5.http.fluent.Request; import org.apache.hc.core5.http.ContentType; import org.apache.hc.core5.http.HttpEntity; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; /** * Import a YFX file via the Yellowfin REST API */ public class ImportYFXFile { public static void main(String[] args) throws Exception { System.out.println("Import YFX File"); String host = "http://localhost:8080/Yellowfin"; String restUsername = "admin@yellowfin.com.au"; String restPassword = "test"; String fileToImport = "/Downloads/Test.yfx"; Path importFile = Paths.get(fileToImport); byte[] fileContents = Files.readAllBytes(importFile); String token = generateToken(host, restUsername, restPassword); // Upload File for initial analysis, and to fetch the number of import items. HttpEntity getImportFileContentMulitpartEntity = MultipartEntityBuilder .create() .setMode(HttpMultipartMode.LEGACY) .setCharset(Charset.forName("UTF-8")) .addBinaryBody("contentToProcess", fileContents , ContentType.DEFAULT_BINARY, importFile.getFileName().toString()) .build(); System.out.println("Getting Import File Contents"); Content getImportContentContent = Request.post(host + "/api/rpc/import-export/get-import-content") .addHeader("Authorization", "YELLOWFIN ts=" + System.currentTimeMillis() + " , nonce=" + new Random().nextLong() + ", token=" + token) .addHeader("Accept", "application/vnd.yellowfin.api-v1+json") .addHeader("Content-Type", getImportFileContentMulitpartEntity.getContentType()) .addHeader("cache-control", "no-cache") .body(getImportFileContentMulitpartEntity) .execute() .returnContent(); JsonObject jsonObject = new JsonParser().parse(getImportContentContent.asString()).getAsJsonObject(); JsonElement itemList = jsonObject.get("items"); JsonArray items = itemList.getAsJsonArray(); // List content, and generate importOptions for each item, setting it to SKIP=false and OPTION=ADD. String importOptions = ""; for (int i=0; i < items.size(); i++ ) { JsonObject item = items.getAsJsonArray().get(i).getAsJsonObject(); System.out.println("Item " + i + " " + item.get("resourceType").getAsString() + " " + item.get("resourceName").getAsString() + " found"); if (i>0) { importOptions = importOptions + ","; } importOptions = importOptions + "{ \"itemIndex\": " + i + ", \"optionKey\": \"SKIP\", \"optionValue\": false }, { \"itemIndex\": " + i + ", \"optionKey\": \"OPTION\", \"optionValue\": \"ADD\" }"; } // Upload File for for import, with import options populated HttpEntity importContentMultipartEntity = MultipartEntityBuilder .create() .setMode(HttpMultipartMode.LEGACY) .setCharset(Charset.forName("UTF-8")) .addBinaryBody("contentToProcess", fileContents , ContentType.DEFAULT_BINARY, importFile.getFileName().toString()) .addTextBody("importOptions", "[" + importOptions + "]", ContentType.APPLICATION_JSON) .build(); System.out.println("Importing Content"); Content importContentContent = Request.post(host + "/api/rpc/import-export/import-content") .addHeader("Authorization", "YELLOWFIN ts=" + System.currentTimeMillis() + " , nonce=" + new Random().nextLong() + ", token=" + token) .addHeader("Accept", "application/vnd.yellowfin.api-v1+json") .addHeader("Content-Type", importContentMultipartEntity.getContentType()) .addHeader("cache-control", "no-cache") .body(importContentMultipartEntity) .execute() .returnContent(); System.out.println("Content Import Complete"); System.out.println(importContentContent.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 | ||||
---|---|---|---|---|
| ||||
package main import ( "bytes" "encoding/json" "fmt" "io/ioutil" "math/rand" "mime/multipart" "net/http" "path/filepath" "strings" "time" ) func main() { fmt.Println("Import YFX File") host := "http://localhost:8080/Yellowfin" restUsername := "admin@yellowfin.com.au" restPassword := "test" fileToImport := "/Downloads/Test.yfx" fileContents, err := ioutil.ReadFile(fileToImport) if err != nil { fmt.Println("Error reading file:", err) return } token, err := generateToken(host, restUsername, restPassword) if err != nil { fmt.Println("Error generating token:", err) return } // Upload File for initial analysis, and to fetch the number of import items. var buf bytes.Buffer writer := multipart.NewWriter(&buf) part, err := writer.CreateFormFile("contentToProcess", filepath.Base(fileToImport)) if err != nil { fmt.Println("Error creating form file:", err) return } part.Write(fileContents) writer.Close() req, err := http.NewRequest("POST", fmt.Sprintf("%s/api/rpc/import-export/get-import-content", host), &buf) 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", writer.FormDataContentType()) req.Header.Set("cache-control", "no-cache") client := &http.Client{} resp, err := client.Do(req) if err != nil { fmt.Println("Error sending request:", err) return } defer resp.Body.Close() getImportContentContent, err := ioutil.ReadAll(resp.Body) if err != nil { fmt.Println("Error reading response body:", err) return } var jsonObject map[string]interface{} if err := json.Unmarshal(getImportContentContent, &jsonObject); err != nil { fmt.Println("Error parsing JSON response:", err) return } items := jsonObject["items"].([]interface{}) var importOptions strings.Builder for i, item := range items { itemMap := item.(map[string]interface{}) fmt.Printf("Item %d %s %s found\n", i, itemMap["resourceType"].(string), itemMap["resourceName"].(string)) if i > 0 { importOptions.WriteString(",") } importOptions.WriteString(fmt.Sprintf(`{ "itemIndex": %d, "optionKey": "SKIP", "optionValue": false }, { "itemIndex": %d, "optionKey": "OPTION", "optionValue": "ADD" }`, i, i)) } // Upload File for import, with import options populated buf.Reset() writer = multipart.NewWriter(&buf) part, err = writer.CreateFormFile("contentToProcess", filepath.Base(fileToImport)) if err != nil { fmt.Println("Error creating form file:", err) return } part.Write(fileContents) writer.WriteField("importOptions", fmt.Sprintf("[%s]", importOptions.String())) writer.Close() req, err = http.NewRequest("POST", fmt.Sprintf("%s/api/rpc/import-export/import-content", host), &buf) if err != nil { fmt.Println("Error creating request:", err) return } 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", writer.FormDataContentType()) req.Header.Set("cache-control", "no-cache") resp, err = client.Do(req) if err != nil { fmt.Println("Error sending request:", err) return } defer resp.Body.Close() importContentContent, err := ioutil.ReadAll(resp.Body) if err != nil { fmt.Println("Error reading response body:", err) return } fmt.Println("Content Import Complete") fmt.Println(string(importContentContent)) } /* * This function generates an access token for a user that will grant them access to * call REST API endpoints. */ 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 { fmt.Println("Error marshaling request body:", err) return "", err } client := &http.Client{} request, err := http.NewRequest("POST", fmt.Sprintf("%s/api/refresh-tokens", host), 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{} if err := json.Unmarshal(responseBody, &jsonResponse); 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 } |
...