Best Practices: Data Development, Submission, and Execution with OpenAPI

Updated at:

DataWorks offers a comprehensive set of OpenAPIs for various business scenarios. This practice demonstrates how to use OpenAPIs to efficiently develop, submit, and execute data tasks.

Background Information

This practice covers the following scenarios. Familiarize yourself with the core capabilities and concepts first.

  • Manage Workspaces, Workflows, folders, and nodes, and submit and deploy tasks. These actions use data development OpenAPIs, such as CreateBusiness and ListBusiness.

  • Run smoke tests and view logs. These actions use Operation Center OpenAPIs, such as RunSmokeTest.

Upon completion, you will be able to set up a local environment for data development, submission, and execution, as shown below.

The following sections describe the core procedures and code examples.

  1. Backend code development

  2. Frontend code development

  3. Local Deployment and Execution

If you want to view or download the full source code examples, see Github code example.

Backend code development

Step 1: Create the ProjectService class to obtain Workspaces

Create a ProjectService class and define the ListProjects function to call ListProjects. This function returns a Workspace list to populate the frontend drop-down menu.

package com.aliyun.dataworks.services;

import com.aliyun.dataworks_public20200518.models.ListProjectsRequest;
import com.aliyun.dataworks_public20200518.models.ListProjectsResponse;
import com.aliyun.dataworks_public20200518.models.ListProjectsResponseBody;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class ProjectService {

    @Autowired
    private DataWorksOpenApiClient dataWorksOpenApiClient;

    /**
     * @param pageNumber
     * @param pageSize
     * @return
     */
    public ListProjectsResponseBody.ListProjectsResponseBodyPageResult listProjects(Integer pageNumber, Integer pageSize) {
        try {
            ListProjectsRequest listProjectsRequest = new ListProjectsRequest();
            listProjectsRequest.setPageNumber(pageNumber);
            listProjectsRequest.setPageSize(pageSize);
            ListProjectsResponse listProjectsResponse = dataWorksOpenApiClient.createClient().listProjects(listProjectsRequest);
            System.out.println(listProjectsResponse.getBody().getRequestId());
            return listProjectsResponse.getBody().getPageResult();
        } catch (Exception e) {
            e.printStackTrace();
            // Error Message
            System.out.println(e.getMessage());
        }
        return null;
    }
}

Step 2: Create the BusinessService class to handle Workflows

Create a BusinessService class and define the following functions:

  • Define createBusiness to call CreateBusiness for Workflow creation.

  • Define listBusiness to call ListBusiness to retrieve a Workflow list.

The frontend uses these functions to create sample Workflows and retrieve lists.

Note

Optionally, define a FolderService to display the directory tree (consisting of Workflows, node folders, and nodes). The following example omits steps related to node folders and focuses on the core process. You can find the FolderService function for folder operations in the full sample code on GitHub at Github code example.

package com.aliyun.dataworks.services;

import com.aliyun.dataworks.dto.CreateBusinessDTO;
import com.aliyun.dataworks.dto.DeleteBusinessDTO;
import com.aliyun.dataworks.dto.ListBusinessesDTO;
import com.aliyun.dataworks.dto.UpdateBusinessDTO;
import com.aliyun.dataworks_public20200518.models.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @author dataworks demo
 */
@Service
public class BusinessService {

    @Autowired
    private DataWorksOpenApiClient dataWorksOpenApiClient;

    /**
     * create a business
     *
     * @param createBusinessDTO
     */
    public Long createBusiness(CreateBusinessDTO createBusinessDTO) {
        try {
            CreateBusinessRequest createBusinessRequest = new CreateBusinessRequest();
            // Name of the Workflow
            createBusinessRequest.setBusinessName(createBusinessDTO.getBusinessName());
            createBusinessRequest.setDescription(createBusinessDTO.getDescription());
            createBusinessRequest.setOwner(createBusinessDTO.getOwner());
            createBusinessRequest.setProjectId(createBusinessDTO.getProjectId());
            // The functional module to which the Workflow belongs. NORMAL (Data Development) MANUAL_BIZ (Manual Workflow)
            createBusinessRequest.setUseType(createBusinessDTO.getUseType());
            CreateBusinessResponse createBusinessResponse = dataWorksOpenApiClient.createClient().createBusiness(createBusinessRequest);
            System.out.println("create business requestId:" + createBusinessResponse.getBody().getRequestId());
            System.out.println("create business successful,the businessId:" + createBusinessResponse.getBody().getBusinessId());
            return createBusinessResponse.getBody().getBusinessId();
        } catch (Exception e) {
            e.printStackTrace();
            // Error Message
            System.out.println(e.getMessage());
        }
        return null;
    }

    /**
     * @param listBusinessesDTO
     * @return
     */
    public List<ListBusinessResponseBody.ListBusinessResponseBodyDataBusiness> listBusiness(ListBusinessesDTO listBusinessesDTO) {
        try {
            ListBusinessRequest listBusinessRequest = new ListBusinessRequest();
            listBusinessRequest.setKeyword(listBusinessesDTO.getKeyword());
            listBusinessRequest.setPageNumber(listBusinessesDTO.getPageNumber() < 1 ? 1 : listBusinessesDTO.getPageNumber());
            listBusinessRequest.setPageSize(listBusinessesDTO.getPageSize() < 10 ? 10 : listBusinessesDTO.getPageSize());
            listBusinessRequest.setProjectId(listBusinessesDTO.getProjectId());
            ListBusinessResponse listBusinessResponse = dataWorksOpenApiClient.createClient().listBusiness(listBusinessRequest);
            System.out.println("list business requestId:" + listBusinessResponse.getBody().getRequestId());
            ListBusinessResponseBody.ListBusinessResponseBodyData data = listBusinessResponse.getBody().getData();
            System.out.println("total count:" + data.getTotalCount());
            if (!CollectionUtils.isEmpty(data.getBusiness())) {
                for (ListBusinessResponseBody.ListBusinessResponseBodyDataBusiness businessItem : data.getBusiness()) {
                    System.out.println(businessItem.getBusinessId() + "," + businessItem.getBusinessName() + "," + businessItem.getUseType());
                }
            }
            return data.getBusiness();
        } catch (Exception e) {
            e.printStackTrace();
            // Error Message
            System.out.println(e.getMessage());
        }
        return null;
    }

    /**
     * update a business
     * @param updateBusinessDTO
     * @return
     */
    public Boolean updateBusiness(UpdateBusinessDTO updateBusinessDTO) {
        try {
            UpdateBusinessRequest updateBusinessRequest = new UpdateBusinessRequest();
            updateBusinessRequest.setBusinessId(updateBusinessDTO.getBusinessId());
            updateBusinessRequest.setBusinessName(updateBusinessDTO.getBusinessName());
            updateBusinessRequest.setDescription(updateBusinessDTO.getDescription());
            updateBusinessRequest.setOwner(updateBusinessDTO.getOwner());
            updateBusinessRequest.setProjectId(updateBusinessDTO.getProjectId());
            UpdateBusinessResponse updateBusinessResponse = dataWorksOpenApiClient.createClient().updateBusiness(updateBusinessRequest);
            System.out.println(updateBusinessResponse.getBody().getRequestId());
            System.out.println(updateBusinessResponse.getBody().getSuccess());
            return updateBusinessResponse.getBody().getSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            // Error Message
            System.out.println(e.getMessage());
        }
        return false;
    }

    /**
     * delete a business
     * @param deleteBusinessDTO
     */
    public boolean deleteBusiness(DeleteBusinessDTO deleteBusinessDTO) {
        try {
            DeleteBusinessRequest deleteBusinessRequest = new DeleteBusinessRequest();
            deleteBusinessRequest.setBusinessId(deleteBusinessDTO.getBusinessId());
            deleteBusinessRequest.setProjectId(deleteBusinessDTO.getProjectId());
            DeleteBusinessResponse deleteBusinessResponse = dataWorksOpenApiClient.createClient().deleteBusiness(deleteBusinessRequest);
            System.out.println("delete business:" + deleteBusinessResponse.getBody().getRequestId());
            System.out.println("delete business" + deleteBusinessResponse.getBody().getSuccess());
            return deleteBusinessResponse.getBody().getSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            // Error Message
            System.out.println(e.getMessage());
        }
        return false;
    }
}

Step 3: Create the FileService class to handle file operations

Create a FileService class to manage file operations:

  • Define listFiles to call ListFiles to retrieve a file list.

  • Define createFile to call CreateFile to create a file.

  • Define updateFile to call UpdateFile to update a file.

  • Define deployFile to call DeployFile to deploy a file.

  • Define runSmokeTest to call RunSmokeTest to run a smoke test.

  • Define getInstanceLog to call GetInstanceLog to retrieve the logs of the smoke test process.

The frontend calls these methods to create, list, save, submit, and execute files.

package com.aliyun.dataworks.services;
import com.aliyun.dataworks.dto.*;
import com.aliyun.dataworks_public20200518.models.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * the ide files manager service
 *
 * @author dataworks demo
 */
@Service
public class FileService {

    @Autowired
    private DataWorksOpenApiClient dataWorksOpenApiClient;

    public static final int CYCLE_NUM = 10;

    /**
     * Pagination query
     *
     * @param listFilesDTO
     * @return
     */
    public List<ListFilesResponseBody.ListFilesResponseBodyDataFiles> listFiles(ListFilesDTO listFilesDTO) {
        try {
            ListFilesRequest listFilesRequest = new ListFilesRequest();
            // File path: "Workflow/" + Target Workflow Name + Directory Name + Latest Folder Name
            // Workflow/MyFirstWorkflow/MaxCompute/ods layer, do not add "DataStudio"
            listFilesRequest.setFileFolderPath(listFilesDTO.getFileFolderPath());
            // Code type of the file. Multiple types are supported, separated by commas. Example: 10,23
            listFilesRequest.setFileTypes(listFilesDTO.getFileTypes());
            // Keyword of the file name. Fuzzy match is supported
            listFilesRequest.setKeyword(listFilesDTO.getKeyword());
            // Scheduling Node ID
            listFilesRequest.setNodeId(listFilesDTO.getNodeId());
            // File owner
            listFilesRequest.setOwner(listFilesDTO.getOwner());
            // Page number
            listFilesRequest.setPageNumber(listFilesDTO.getPageNumber() <= 0 ? 1 : listFilesDTO.getPageNumber());
            // Page size
            listFilesRequest.setPageSize(listFilesDTO.getPageSize() <= 10 ? 10 : listFilesDTO.getPageSize());
            // DataWorks Workspace ID
            listFilesRequest.setProjectId(listFilesDTO.getProjectId());
            // Functional module to which the file belongs
            listFilesRequest.setUseType(listFilesDTO.getUseType());
            ListFilesResponse listFilesResponse = dataWorksOpenApiClient.createClient()
                    .listFiles(listFilesRequest);
            ListFilesResponseBody.ListFilesResponseBodyData fileData = listFilesResponse.getBody().getData();
            if (fileData.getFiles() != null && !fileData.getFiles().isEmpty()) {
                for (ListFilesResponseBody.ListFilesResponseBodyDataFiles file : fileData.getFiles()) {
                    // Workflow ID
                    System.out.println(file.getBusinessId());
                    // File ID
                    System.out.println(file.getFileId());
                    // File name
                    System.out.println(file.getFileName());
                    // File type 10
                    System.out.println(file.getFileType());
                    // Node ID
                    System.out.println(file.getNodeId());
                    // Folder ID
                    System.out.println(file.getFileFolderId());
                }
            }
            return fileData.getFiles();
        } catch (Exception e) {
            e.printStackTrace();
            // Error Message
            System.out.println(e.getMessage());
        }
        return null;
    }

    /**
     * Create file
     *
     * @param createFileDTO
     */
    public Long createFile(CreateFileDTO createFileDTO) {
        try {
            CreateFileRequest createFileRequest = new CreateFileRequest();
            // Advanced settings of the task
            createFileRequest.setAdvancedSettings(createFileDTO.getAdvancedSettings());
            // Whether to enable Auto Parsing for the file. Required
            createFileRequest.setAutoParsing(createFileDTO.getAutoParsing());
            // Rerun interval after failure, in milliseconds. Maximum value: 1800000 ms (30 minutes)
            createFileRequest.setAutoRerunIntervalMillis(createFileDTO.getAutoRerunIntervalMillis());
            // Number of automatic reruns
            createFileRequest.setAutoRerunTimes(createFileDTO.getAutoRerunTimes());
            // The data source connected when the task is executed after the file is deployed. Required
            createFileRequest.setConnectionName(createFileDTO.getConnectionName());
            // File code content. Required
            createFileRequest.setContent(createFileDTO.getContent());
            // Cron Expression for cycle scheduling. Required
            createFileRequest.setCronExpress(createFileDTO.getCronExpress());
            // Scheduling Cycle type. Required
            createFileRequest.setCycleType(createFileDTO.getCycleType());
            // List of nodes depended on in the previous cycle
            createFileRequest.setDependentNodeIdList(createFileDTO.getDependentNodeIdList());
            // Dependency type for the previous cycle. Required
            createFileRequest.setDependentType(createFileDTO.getDependentType());
            // Timestamp for stopping automatic scheduling, in milliseconds.
            createFileRequest.setEndEffectDate(createFileDTO.getEndEffectDate());
            // File description
            createFileRequest.setFileDescription(createFileDTO.getFileDescription());
            // File path. Required
            createFileRequest.setFileFolderPath(createFileDTO.getFileFolderPath());
            // File name. Required
            createFileRequest.setFileName(createFileDTO.getFileName());
            // File code type. Required
            createFileRequest.setFileType(createFileDTO.getFileType());
            // Output name of the upstream file that the current file depends on. Separate multiple outputs with commas (,). Required
            createFileRequest.setInputList(createFileDTO.getInputList());
            // Alibaba Cloud UID of the file owner. If this parameter is empty, the Alibaba Cloud UID of the caller is used by default. Required
            createFileRequest.setOwner(createFileDTO.getOwner());
            // Scheduling parameters.
            createFileRequest.setParaValue(createFileDTO.getParaValue());
            // Workspace ID. Required
            createFileRequest.setProjectId(createFileDTO.getProjectId());
            // Rerun mode
            createFileRequest.setRerunMode(createFileDTO.getRerunMode());
            // Resource Group identifier for the task. Required
            createFileRequest.setResourceGroupIdentifier(createFileDTO.getResourceGroupIdentifier());
            // Scheduling type
            createFileRequest.setSchedulerType(createFileDTO.getSchedulerType());
            // Timestamp for starting automatic scheduling, in milliseconds
            createFileRequest.setStartEffectDate(createFileDTO.getStartEffectDate());
            // Whether to pause scheduling
            createFileRequest.setStop(createFileDTO.getStop());
            CreateFileResponse createFileResponse = dataWorksOpenApiClient.createClient()
                    .createFile(createFileRequest);
            // requestId
            System.out.println(createFileResponse.getBody().getRequestId());
            // fileId
            System.out.println(createFileResponse.getBody().getData());
            return createFileResponse.getBody().getData();
        } catch (Exception e) {
            e.printStackTrace();
            // Error Message
            System.out.println(e.getMessage());
        }
        return null;
    }

    /**
     * Update file
     *
     * @param updateFileDTO
     */
    public boolean updateFile(UpdateFileDTO updateFileDTO) {
        try {
            UpdateFileRequest updateFileRequest = new UpdateFileRequest();
            // Advanced settings of the task. For the format, see the documentation
            updateFileRequest.setAdvancedSettings(updateFileDTO.getAdvancedSettings());
            // Whether to enable Auto Parsing for the file
            updateFileRequest.setAutoParsing(updateFileDTO.getAutoParsing());
            // Rerun interval after failure, in milliseconds. Maximum value: 1800000 ms (30 minutes).
            updateFileRequest.setAutoRerunIntervalMillis(updateFileDTO.getAutoRerunIntervalMillis());
            // Number of automatic reruns after failure
            updateFileRequest.setAutoRerunTimes(updateFileDTO.getAutoRerunTimes());
            // The data source identifier used by the task when the corresponding file task is executed
            updateFileRequest.setConnectionName(updateFileDTO.getConnectionName());
            // File code content
            updateFileRequest.setContent(updateFileDTO.getContent());
            // Cron Expression for cycle scheduling
            updateFileRequest.setCronExpress(updateFileDTO.getCronExpress());
            // Scheduling Cycle type, including NOT_DAY (minute, hour) and DAY (day, week, month)
            updateFileRequest.setCycleType(updateFileDTO.getCycleType());
            // When DependentType is set to USER_DEFINE, set the specific Node ID that the current file depends on. Separate multiple Node IDs with commas (,)
            updateFileRequest.setDependentNodeIdList(updateFileDTO.getDependentNodeIdList());
            // Dependency type for the previous cycle
            updateFileRequest.setDependentType(updateFileDTO.getDependentType());
            // Timestamp for stopping automatic scheduling, in milliseconds.
            updateFileRequest.setEndEffectDate(updateFileDTO.getEndEffectDate());
            // File description
            updateFileRequest.setFileDescription(updateFileDTO.getFileDescription());
            // File path
            updateFileRequest.setFileFolderPath(updateFileDTO.getFileFolderPath());
            // File ID
            updateFileRequest.setFileId(updateFileDTO.getFileId());
            // File name
            updateFileRequest.setFileName(updateFileDTO.getFileName());
            // Output name of the upstream file that the current file depends on. Separate multiple outputs with commas (,)
            updateFileRequest.setInputList(updateFileDTO.getInputList());
            // File output
            updateFileRequest.setOutputList(updateFileDTO.getOutputList());
            // Alibaba Cloud UID of the file owner
            updateFileRequest.setOwner(updateFileDTO.getOwner());
            // Scheduling parameters
            updateFileRequest.setParaValue(updateFileDTO.getParaValue());
            // DataWorks Workspace ID
            updateFileRequest.setProjectId(updateFileDTO.getProjectId());
            // Rerun mode ALL_ALLOWED
            updateFileRequest.setRerunMode(updateFileDTO.getRerunMode());
            // Resource Group identifier for the task
            updateFileRequest.setResourceGroupIdentifier(updateFileDTO.getResourceGroupIdentifier());
            // Scheduling type NORMAL
            updateFileRequest.setSchedulerType(updateFileDTO.getSchedulerType());
            // Timestamp for starting automatic scheduling, in milliseconds
            updateFileRequest.setStartEffectDate(updateFileDTO.getStartEffectDate());
            // Whether to start immediately after deployment
            updateFileRequest.setStartImmediately(updateFileDTO.getStartImmediately());
            // Whether to pause scheduling
            updateFileRequest.setStop(updateFileDTO.getStop());
            UpdateFileResponse updateFileResponse = dataWorksOpenApiClient.createClient()
                    .updateFile(updateFileRequest);
            // requestId
            System.out.println(updateFileResponse.getBody().getRequestId());
            // Success or not
            System.out.println(updateFileResponse.getBody().getSuccess());
            return updateFileResponse.getBody().getSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            // Error Message
            System.out.println(e.getMessage());
        }
        return false;
    }

    /**
     * Delete a file
     *
     * @param deleteFileDTO
     * @return
     * @throws InterruptedException
     */
    public boolean deleteFile(DeleteFileDTO deleteFileDTO) throws InterruptedException {
        try {
            DeleteFileRequest deleteFileRequest = new DeleteFileRequest();
            deleteFileRequest.setFileId(deleteFileDTO.getFileId());
            deleteFileRequest.setProjectId(deleteFileDTO.getProjectId());
            DeleteFileResponse deleteFileResponse = dataWorksOpenApiClient.createClient()
                    .deleteFile(deleteFileRequest);
            System.out.println(deleteFileResponse.getBody().getRequestId());
            System.out.println(deleteFileResponse.getBody().getDeploymentId());


            GetDeploymentRequest getDeploymentRequest = new GetDeploymentRequest();
            getDeploymentRequest.setProjectId(deleteFileDTO.getProjectId());
            getDeploymentRequest.setDeploymentId(deleteFileResponse.getBody().getDeploymentId());
            for (int i = 0; i < CYCLE_NUM; i++) {
                GetDeploymentResponse getDeploymentResponse = dataWorksOpenApiClient.createClient()
                        .getDeployment(getDeploymentRequest);
                // Current status of the Deployment Package, including 0 (Ready), 1 (Success), and 2 (Failed).
                Integer deleteStatus = getDeploymentResponse.getBody().getData().getDeployment().getStatus();
                // Loop to check the deletion status here
                if (deleteStatus == 1) {
                    System.out.println("File deleted successfully.");
                    break;
                } else {
                    System.out.println("Deleting file");
                    Thread.sleep(1000L);
                }
            }

            GetProjectRequest getProjectRequest = new GetProjectRequest();
            getProjectRequest.setProjectId(deleteFileDTO.getProjectId());
            GetProjectResponse getProjectResponse = dataWorksOpenApiClient.createClient()
                    .getProject(getProjectRequest);
            // Standard Mode has DEV and PROD environments, while Simple Mode only has PROD
            Boolean standardMode = getProjectResponse.getBody().getData().getEnvTypes().size() == 2;
            if (standardMode) {
                // In Standard Mode, deletion needs to be deployed to the production environment
                DeployFileRequest deployFileRequest = new DeployFileRequest();
                deployFileRequest.setProjectId(deleteFileDTO.getProjectId());
                deployFileRequest.setFileId(deleteFileDTO.getFileId());
                DeployFileResponse deployFileResponse = dataWorksOpenApiClient.createClient()
                        .deployFile(deployFileRequest);
                getDeploymentRequest.setDeploymentId(deployFileResponse.getBody().getData());
                for (int i = 0; i < CYCLE_NUM; i++) {
                    GetDeploymentResponse getDeploymentResponse = dataWorksOpenApiClient.createClient()
                            .getDeployment(getDeploymentRequest);
                    // Current status of the Deployment Package, including 0 (Ready), 1 (Success), and 2 (Failed).
                    Integer deleteStatus = getDeploymentResponse.getBody().getData().getDeployment().getStatus();
                    // Loop to check the deletion status here
                    if (deleteStatus == 1) {
                        System.out.println("File deleted successfully.");
                        break;
                    } else {
                        System.out.println("Deleting file");
                        Thread.sleep(1000L);
                    }
                }
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            // Error Message
            System.out.println(e.getMessage());
        }
        return false;
    }

    /**
     * Query file
     *
     * @param getFileDTO
     */
    public GetFileResponseBody.GetFileResponseBodyDataFile getFile(GetFileDTO getFileDTO) {
        try {
            GetFileRequest getFileRequest = new GetFileRequest();
            getFileRequest.setFileId(getFileDTO.getFileId());
            getFileRequest.setProjectId(getFileDTO.getProjectId());
            getFileRequest.setNodeId(getFileDTO.getNodeId());
            GetFileResponse getFileResponse = dataWorksOpenApiClient.createClient().getFile(getFileRequest);
            System.out.println(getFileResponse.getBody().getRequestId());
            GetFileResponseBody.GetFileResponseBodyDataFile file = getFileResponse.getBody().getData().getFile();
            System.out.println(file.getFileName());
            System.out.println(file.getFileType());
            System.out.println(file.getNodeId());
            System.out.println(file.getCreateUser());
            return file;
        } catch (Exception e) {
            e.printStackTrace();
            // Error Message
            System.out.println(e.getMessage());
        }
        return null;
    }

    /**
     * @param deployFileDTO
     * @return
     * @throws InterruptedException
     */
    public Boolean deployFile(DeployFileDTO deployFileDTO) throws InterruptedException {
        try {
            GetProjectRequest getProjectRequest = new GetProjectRequest();
            getProjectRequest.setProjectId(deployFileDTO.getProjectId());
            GetProjectResponse getProjectResponse = dataWorksOpenApiClient.createClient()
                    .getProject(getProjectRequest);
            // Standard Mode has DEV and PROD environments, while Simple Mode only has PROD
            Boolean standardMode = getProjectResponse.getBody().getData().getEnvTypes().size() == 2;
            if (standardMode) {
                SubmitFileRequest submitFileRequest = new SubmitFileRequest();
                submitFileRequest.setFileId(deployFileDTO.getFileId());
                submitFileRequest.setProjectId(deployFileDTO.getProjectId());
                SubmitFileResponse submitFileResponse = dataWorksOpenApiClient.createClient()
                        .submitFile(submitFileRequest);
                System.out.println("submit file requestId:" + submitFileResponse.getBody().getRequestId());
                System.out.println("submit file deploymentId:" + submitFileResponse.getBody().getData());
                for (int i = 0; i < CYCLE_NUM; i++) {
                    GetDeploymentRequest getDeploymentRequest = new GetDeploymentRequest();
                    getDeploymentRequest.setProjectId(deployFileDTO.getProjectId());
                    getDeploymentRequest.setDeploymentId(submitFileResponse.getBody().getData());
                    GetDeploymentResponse getDeploymentResponse = dataWorksOpenApiClient.createClient()
                            .getDeployment(getDeploymentRequest);
                    // Current status of the Deployment Package, including 0 (Ready), 1 (Success), and 2 (Failed).
                    Integer deleteStatus = getDeploymentResponse.getBody().getData().getDeployment().getStatus();
                    // Loop to check the deletion status here
                    if (deleteStatus == 1) {
                        System.out.println("File submitted successfully.");
                        break;
                    } else {
                        System.out.println("Submitting file...");
                        Thread.sleep(1000L);
                    }
                }
            }
            DeployFileRequest deployFileRequest = new DeployFileRequest();
            deployFileRequest.setFileId(deployFileDTO.getFileId());
            deployFileRequest.setProjectId(deployFileDTO.getProjectId());
            DeployFileResponse deployFileResponse = dataWorksOpenApiClient.createClient()
                    .deployFile(deployFileRequest);
            System.out.println("deploy file requestId:" + deployFileResponse.getBody().getRequestId());
            System.out.println("deploy file deploymentId:" + deployFileResponse.getBody().getData());
            for (int i = 0; i < CYCLE_NUM; i++) {
                GetDeploymentRequest getDeploymentRequest = new GetDeploymentRequest();
                getDeploymentRequest.setProjectId(deployFileDTO.getProjectId());
                getDeploymentRequest.setDeploymentId(deployFileResponse.getBody().getData());
                GetDeploymentResponse getDeploymentResponse = dataWorksOpenApiClient.createClient()
                        .getDeployment(getDeploymentRequest);
                // Current status of the Deployment Package, including 0 (Ready), 1 (Success), and 2 (Failed).
                Integer deleteStatus = getDeploymentResponse.getBody().getData().getDeployment().getStatus();
                // Loop to check the deletion status here
                if (deleteStatus == 1) {
                    System.out.println("File deployed successfully.");
                    break;
                } else {
                    System.out.println("Deploying file...");
                    Thread.sleep(1000L);
                }
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            // Error Message
            System.out.println(e.getMessage());
        }
        return false;
    }

    public List<ListInstancesResponseBody.ListInstancesResponseBodyDataInstances> runSmokeTest(RunSmokeTestDTO runSmokeTestDTO) {
        try {
            RunSmokeTestRequest runSmokeTestRequest = new RunSmokeTestRequest();
            runSmokeTestRequest.setBizdate(runSmokeTestDTO.getBizdate());
            runSmokeTestRequest.setNodeId(runSmokeTestDTO.getNodeId());
            runSmokeTestRequest.setNodeParams(runSmokeTestDTO.getNodeParams());
            runSmokeTestRequest.setName(runSmokeTestDTO.getName());
            runSmokeTestRequest.setProjectEnv(runSmokeTestDTO.getProjectEnv());
            RunSmokeTestResponse runSmokeTestResponse = dataWorksOpenApiClient.createClient()
                    .runSmokeTest(runSmokeTestRequest);
            System.out.println(runSmokeTestResponse.getBody().getRequestId());
            // DAGID
            System.out.println(runSmokeTestResponse.getBody().getData());


            ListInstancesRequest listInstancesRequest = new ListInstancesRequest();
            listInstancesRequest.setDagId(runSmokeTestResponse.getBody().getData());
            listInstancesRequest.setProjectId(runSmokeTestDTO.getProjectId());
            listInstancesRequest.setProjectEnv(runSmokeTestDTO.getProjectEnv());
            listInstancesRequest.setNodeId(runSmokeTestDTO.getNodeId());
            listInstancesRequest.setPageNumber(1);
            listInstancesRequest.setPageSize(10);
            ListInstancesResponse listInstancesResponse = dataWorksOpenApiClient.createClient()
                    .listInstances(listInstancesRequest);
            System.out.println(listInstancesResponse.getBody().getRequestId());
            List<ListInstancesResponseBody.ListInstancesResponseBodyDataInstances> instances = listInstancesResponse.getBody().getData().getInstances();
            if (CollectionUtils.isEmpty(instances)) {
                return null;
            }
            return instances;
        } catch (Exception e) {
            e.printStackTrace();
            // Error Message
            System.out.println(e.getMessage());
        }
        return null;
    }


    public InstanceDetail getInstanceLog(Long instanceId, String projectEnv) {
        try {
            GetInstanceLogRequest getInstanceLogRequest = new GetInstanceLogRequest();
            getInstanceLogRequest.setInstanceId(instanceId);
            getInstanceLogRequest.setProjectEnv(projectEnv);
            GetInstanceLogResponse getInstanceLogResponse = dataWorksOpenApiClient.createClient()
                    .getInstanceLog(getInstanceLogRequest);
            System.out.println(getInstanceLogResponse.getBody().getRequestId());


            GetInstanceRequest getInstanceRequest = new GetInstanceRequest();
            getInstanceRequest.setInstanceId(instanceId);
            getInstanceRequest.setProjectEnv(projectEnv);
            GetInstanceResponse getInstanceResponse = dataWorksOpenApiClient.createClient()
                    .getInstance(getInstanceRequest);
            System.out.println(getInstanceResponse.getBody().getRequestId());
            System.out.println(getInstanceResponse.getBody().getData());


            InstanceDetail instanceDetail = new InstanceDetail();
            instanceDetail.setInstance(getInstanceResponse.getBody().getData());
            instanceDetail.setInstanceLog(getInstanceLogResponse.getBody().getData());
            return instanceDetail;
        } catch (Exception e) {
            e.printStackTrace();
            // Error Message
            System.out.println(e.getMessage());
        }
        return null;
    }
}

Step 4: Create the IdeController

Define an IdeController to provide API routes for the frontend.

package com.aliyun.dataworks.demo;


import com.aliyun.dataworks.dto.*;
import com.aliyun.dataworks.services.BusinessService;
import com.aliyun.dataworks.services.FileService;
import com.aliyun.dataworks.services.FolderService;
import com.aliyun.dataworks.services.ProjectService;
import com.aliyun.dataworks_public20200518.models.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


import java.util.List;


/**
 * @author dataworks demo
 */
@RestController
@RequestMapping("/ide")
public class IdeController {


    @Autowired
    private FileService fileService;


    @Autowired
    private FolderService folderService;


    @Autowired
    private BusinessService businessService;


    @Autowired
    private ProjectService projectService;


    /**
     * List files
     *
     * @param listFilesDTO
     * @return ListFilesResponse.Data.File
     */
    @CrossOrigin(origins = "http://localhost:8080")
    @GetMapping("/listFiles")
    public List<ListFilesResponseBody.ListFilesResponseBodyDataFiles> listFiles(ListFilesDTO listFilesDTO) {
        return fileService.listFiles(listFilesDTO);
    }


    /**
     * List folders
     *
     * @param listFoldersDTO
     * @return ListFoldersResponse.Data.FoldersItem
     */
    @CrossOrigin(origins = "http://localhost:8080")
    @GetMapping("/listFolders")
    public List<ListFoldersResponseBody.ListFoldersResponseBodyDataFolders> listFolders(ListFoldersDTO listFoldersDTO) {
        return folderService.listFolders(listFoldersDTO);
    }


    /**
     * Create a folder
     *
     * @param createFolderDTO
     * @return boolean
     */
    @CrossOrigin(origins = "http://localhost:8080")
    @PostMapping("/createFolder")
    public boolean createFolder(@RequestBody CreateFolderDTO createFolderDTO) {
        return folderService.createFolder(createFolderDTO);
    }


    /**
     * Update a folder
     *
     * @param updateFolderDTO
     * @return boolean
     */
    @CrossOrigin(origins = "http://localhost:8080")
    @PostMapping("/updateFolder")
    public boolean updateFolder(@RequestBody UpdateFolderDTO updateFolderDTO) {
        return folderService.updateFolder(updateFolderDTO);
    }


    /**
     * Get a file
     *
     * @param getFileDTO
     * @return GetFileResponse.Data.File
     */
    @CrossOrigin(origins = "http://localhost:8080")
    @GetMapping("/getFile")
    public GetFileResponseBody.GetFileResponseBodyDataFile getFile(GetFileDTO getFileDTO) {
        return fileService.getFile(getFileDTO);
    }


    /**
     * Create a file
     *
     * @param createFileDTO
     * @return fileId
     */
    @CrossOrigin(origins = "http://localhost:8080")
    @PostMapping("/createFile")
    public Long createFile(@RequestBody CreateFileDTO createFileDTO) {
        return fileService.createFile(createFileDTO);
    }


    /**
     * Update a file
     *
     * @param updateFileDTO
     * @return boolean
     */
    @CrossOrigin(origins = "http://localhost:8080")
    @PostMapping("/updateFile")
    public boolean updateFile(@RequestBody UpdateFileDTO updateFileDTO) {
        return fileService.updateFile(updateFileDTO);
    }


    /**
     * Deploy a file
     *
     * @param deployFileDTO
     * @return boolean
     */
    @CrossOrigin(origins = "http://localhost:8080")
    @PostMapping("/deployFile")
    public boolean deployFile(@RequestBody DeployFileDTO deployFileDTO) {
        try {
            return fileService.deployFile(deployFileDTO);
        } catch (Exception e) {
            System.out.println(e);
        }
        return false;
    }


    /**
     * Delete a file
     *
     * @param deleteFileDTO
     * @return
     */
    @CrossOrigin(origins = "http://localhost:8080")
    @DeleteMapping("/deleteFile")
    public boolean deleteFile(DeleteFileDTO deleteFileDTO) {
        try {
            return fileService.deleteFile(deleteFileDTO);
        } catch (Exception e) {
            System.out.println(e);
        }
        return false;
    }


    /**
     * Delete a folder
     *
     * @param deleteFolderDTO
     * @return
     */
    @CrossOrigin(origins = "http://localhost:8080")
    @DeleteMapping("/deleteFolder")
    public boolean deleteFolder(DeleteFolderDTO deleteFolderDTO) {
        return folderService.deleteFolder(deleteFolderDTO);
    }


    /**
     * List businesses
     *
     * @param listBusinessesDTO
     * @return
     */
    @CrossOrigin(origins = "http://localhost:8080")
    @GetMapping("/listBusinesses")
    public List<ListBusinessResponseBody.ListBusinessResponseBodyDataBusiness> listBusiness(ListBusinessesDTO listBusinessesDTO) {
        return businessService.listBusiness(listBusinessesDTO);
    }


    /**
     * Create a business
     *
     * @param createBusinessDTO
     * @return
     */
    @CrossOrigin(origins = "http://localhost:8080")
    @PostMapping("/createBusiness")
    public Long createBusiness(@RequestBody CreateBusinessDTO createBusinessDTO) {
        return businessService.createBusiness(createBusinessDTO);
    }


    /**
     * Update a business
     *
     * @param updateBusinessDTO
     * @return
     */
    @CrossOrigin(origins = "http://localhost:8080")
    @PostMapping("/updateBusiness")
    public boolean updateBusiness(@RequestBody UpdateBusinessDTO updateBusinessDTO) {
        return businessService.updateBusiness(updateBusinessDTO);
    }


    /**
     * Delete a business
     *
     * @param deleteBusinessDTO
     * @return
     */
    @CrossOrigin(origins = "http://localhost:8080")
    @PostMapping("/deleteBusiness")
    public boolean deleteBusiness(@RequestBody DeleteBusinessDTO deleteBusinessDTO) {
        return businessService.deleteBusiness(deleteBusinessDTO);
    }



    /**
     * @param pageNumber
     * @param pageSize
     * @return
     */
    @CrossOrigin(origins = "http://localhost:8080")
    @GetMapping("/listProjects")
    public ListProjectsResponseBody.ListProjectsResponseBodyPageResult listProjects(Integer pageNumber, Integer pageSize) {
        return projectService.listProjects(pageNumber, pageSize);
    }


    /**
     * @param runSmokeTestDTO
     * @return
     */
    @CrossOrigin(origins = "http://localhost:8080")
    @PutMapping("/runSmokeTest")
    public List<ListInstancesResponseBody.ListInstancesResponseBodyDataInstances> runSmokeTest(@RequestBody RunSmokeTestDTO runSmokeTestDTO) {
        return fileService.runSmokeTest(runSmokeTestDTO);
    }


    /**
     * @param instanceId
     * @param projectEnv
     * @return
     */
    @CrossOrigin(origins = "http://localhost:8080")
    @GetMapping("/getLog")
    public InstanceDetail getLog(@RequestParam Long instanceId, @RequestParam String projectEnv) {
        return fileService.getInstanceLog(instanceId, projectEnv);
    }


}

Frontend code development

  1. Initialize the editor, directory tree, and terminal.

    See the following example:

    const App: FunctionComponent<Props> = () => {
      const editorRef = useRef<HTMLDivElement>(null);
      const termianlRef = useRef<HTMLDivElement>(null);
      const [terminal, setTerminal] = useState<NextTerminal>();
      const [editor, setEditor] = useState<monaco.editor.IStandaloneCodeEditor>();
      const [expnadedKeys, setExpandedKeys] = useState<any[]>();
      const [workspace, setWorkspace] = useState<number>();
      const [workspaces, setWorkspaces] = useState<{ label: string, value: number }[]>([]);
      const [dataSource, setDataSource] = useState<any[]>();
      const [selectedFile, setSelectedFile] = useState<number>();
      const [loading, setLoading] = useState<boolean>(false);
      // Create editor instance
      useEffect(() => {
        if (editorRef.current) {
          const nextEditor = monaco.editor.create(editorRef.current, editorOptions);
          setEditor(nextEditor);
          return () => { nextEditor.dispose(); };
        }
      }, [editorRef.current]);
      // Add key event for saving file
      useEffect(() => {
        editor?.addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyS, () => {
          if (!workspace) {
            showTips('Please select workspace first');
            return;
          }
          saveFile(workspace, editor, selectedFile);
        });
      }, [editor, workspace, selectedFile]);
      // Create terminal instance
      useEffect(() => {
        if (termianlRef.current) {
          const term: NextTerminal = new Terminal(terminalOptions) as any;
          term.pointer = -1;
          term.stack = [];
          setTerminal(term);
          const fitAddon = new FitAddon();
          term.loadAddon(fitAddon);
          term.open(termianlRef.current);
          fitAddon.fit();
          term.write('$ ');
          return () => { term.dispose(); };
        }
      }, [termianlRef.current]);
      // Register terminal input event
      useEffect(() => {
        const event = terminal?.onKey(e => onTerminalKeyChange(e, terminal, dataSource, workspace));
        return () => {
          event?.dispose();
        };
      }, [terminal, dataSource, workspace]);
      // Get directory tree data source
      useEffect(() => {
        workspace && (async () => {
          setLoading(true);
          const nextDataSource = await getTreeDataSource(workspace, workspaces);
          const defaultKey = nextDataSource?.[0]?.key;
          defaultKey && setExpandedKeys([defaultKey]);
          setDataSource(nextDataSource);
          setLoading(false);
        })();
      }, [workspace]);
      // When a file in the directory tree is clicked, get file details and display code
      useEffect(() => {
        workspace && selectedFile && (async () => {
          setLoading(true);
          const file = await getFileInfo(workspace, selectedFile);
          editor?.setValue(file.content);
          editor?.getAction('editor.action.formatDocument').run();
          setLoading(false);
        })();
      }, [selectedFile]);
      // Get Workspace list
      useEffect(() => {
        (async () => {
          const list = await getWorkspaceList();
          setWorkspaces(list);
        })();
      }, []);
      const onExapnd = useCallback((keys: number[]) => { setExpandedKeys(keys); }, []);
      const onWorkspaceChange = useCallback((value: number) => { setWorkspace(value) }, []);
      const onTreeNodeSelect = useCallback((key: number[]) => { key[0] && setSelectedFile(key[0]) }, []);
      return (
        <div className={cn(classes.appWrapper)}>
          <div className={cn(classes.leftArea)}>
            <div className={cn(classes.workspaceWrapper)}>
              Workspace:
              <Select
                value={workspace}
                dataSource={workspaces}
                onChange={onWorkspaceChange}
                autoWidth={false}
                showSearch
              />
            </div>
            <div className={cn(classes.treeWrapper)}>
              <Tree
                dataSource={dataSource}
                isNodeBlock={{ defaultPaddingLeft: 20 }}
                expandedKeys={expnadedKeys}
                selectedKeys={[selectedFile]}
                onExpand={onExapnd}
                onSelect={onTreeNodeSelect}
                defaultExpandAll
              />
            </div>
          </div>
          <div className={cn(classes.rightArea)}>
            <div
              className={cn(classes.monacoEditorWrapper)}
              ref={editorRef}
            />
            <div
              className={cn(classes.panelWrapper)}
              ref={termianlRef}
            />
          </div>
          <div className={cn(classes.loaderLine)} style={{ display: loading ? 'block' : 'none' }} />
        </div>
      );
    };
                            
  2. Retrieve the example Workflow and files to populate the directory tree.

    The following code demonstrates the process.流程图1

    /**
     * Get directory tree data source
     * @param workspace Workspace ID
     * @param dataSource Workspace list
     */
    async function getTreeDataSource(workspace: number, dataSource: { label: string, value: number }[]) {
      try {
        const businesses = await services.ide.getBusinessList(workspace, openPlatformBusinessName);
        businesses.length === 0 && await services.ide.createBusiness(workspace, openPlatformBusinessName);
      } catch (e) {
        showError('You have no permission to access this workspace.');
        return;
      }
      const fileFolderPath = `Workflow/${openPlatformBusinessName}/MaxCompute`;
      const files = await services.ide.getFileList(workspace, fileFolderPath);
      let children: { key: number, label: string }[] = [];
      if (files.length === 0) {
        try {
          const currentWorkspace = dataSource.find(i => i.value === workspace);
          const file1 = await services.ide.createFile(workspace, currentWorkspace!.label, fileFolderPath, 'simpleSQL.mc.sql', 'SELECT 1');
          const file2 = await services.ide.createFile(workspace, currentWorkspace!.label, fileFolderPath, 'createTable.mc.sql', 'CREATE TABLE IF NOT EXISTS _qcc_mysql1_odps_source_20220113100903_done_ (\ncol string\n)\nCOMMENT \'Table indicating full data synchronization is DONE\'\nPARTITIONED BY\n(\nstatus STRING   COMMENT \'Partition indicating DONE\'\n)\nLIFECYCLE 36500;');
          children = children.concat([
            { key: file1, label: 'simpleSQL.mc.sql' },
            { key: file2, label: 'createTable.mc.sql' },
          ]);
        } catch (e) {
          showError('Create file failed. The datasource odps_source does not exist.');
          return;
        }
      } else {
        children = files.map((i) => ({ key: i.fileId, label: i.fileName }));
      }
      return [{ key: 1, label: openPlatformBusinessName, children }];
    }
  3. When a user edits and saves a file, send the content to the backend for updates.

    The following sample code provides an example.

    /**
     * Save file, triggered by Ctrl+S
     * @param workspace Workspace ID
     * @param editor Editor instance
     * @param selectedFile Selected file
     */
    async function saveFile(workspace: number, editor: monaco.editor.IStandaloneCodeEditor, selectedFile?: number) {
      if (!selectedFile) {
        showTips('Please select a file.');
        return;
      }
      const content = editor.getValue();
      const result = await services.ide.updateFile(workspace, selectedFile, { content });
      result ? showTips('Saved file') : showError('Failed to save file');
    }
  4. When a user enters dw run ... in the terminal, submit the file to the scheduling system and execute a smoke test.

    The following sample code shows the processing logic.流程2

    /**
     * Handle Terminal keyboard events
     * @param e Event object
     * @param term Terminal instance
     * @param dataSource Directory tree data source
     * @param workspace Workspace ID
     */
    function onTerminalKeyChange(e: { key: string; domEvent: KeyboardEvent; }, term: NextTerminal, dataSource: any, workspace?: number) {
      const ev = e.domEvent;
      const printable = !ev.altKey && !ev.ctrlKey && !ev.metaKey;
      term.inputText = typeof term.inputText === 'string' ? term.inputText : '';
      switch (ev.key) {
        case 'ArrowUp':
          term.pointer = term.pointer < (term.stack.length - 1) ? term.pointer + 1 : term.pointer;
          term.inputText = term.stack[term.pointer];
          term.write(`\x1b[2K\r$ ${term.inputText}`);
          break;
        case 'ArrowDown':
          term.pointer = term.pointer > -1 ? term.pointer - 1 : -1;
          term.inputText = term.pointer === -1 ? '' : term.stack[term.pointer];
          term.write(`\x1b[2K\r$ ${term.inputText}`);
          break;
        case 'ArrowLeft':
          (term as any)._core.buffer.x > 2 && printable && term.write(e.key);
          break;
        case 'ArrowRight':
          (term as any)._core.buffer.x <= (term.inputText.length + 1) && printable && term.write(e.key);
          break;
        case 'Enter':
          commandHandler(term, dataSource, workspace);
          break;
        case 'Backspace':
          if ((term as any)._core.buffer.x > 2) {
            term.inputText = term.inputText.slice(0, -1);
            term.write('\b \b');
          }
          break;
        default:
          if (printable) {
            term.inputText += e.key;
            term.write(e.key);
          }
      }
    }
    /**
     * Method to handle task submission, triggered when "dw run ..." is entered in the terminal
     * @param term Terminal instance
     * @param dataSource Directory tree data source
     * @param workspace Workspace ID
     */
    async function commandHandler(term: NextTerminal, dataSource: any, workspace?: number) {
      term.write('\r\n$ ');
      const input = term.inputText;
      term.inputText = '';
      if (['', undefined].includes(input)) {
        return;
      }
      term.stack = [input!, ...term.stack];
      term.pointer = -1;
      if (!workspace) {
        term.write(highlight.text('[ERROR] You should select workspace first.\r\n$ ', brush));
        return;
      }
      // Simple parsing of the input command line. If the command starts with "dw" and the execution command is "run", proceed; otherwise, report an error
      const words = input?.split(' ');
      const tag = words?.[0].toLowerCase();
      const command = words?.[1]?.toLowerCase();
      const fileName = words?.[2];
      if (tag !== 'dw' || !validCommands.includes(command!)) {
        term.write(highlight.text('[ERROR] Invalid command.\r\n$ ', brush));
        return;
      }
      // Get input file
      const source = dataSource?.[0]?.children.find((i: any) => i.label === fileName);
      const file = await services.ide.getFile(workspace, source.key);
      if (!file) {
        term.write(highlight.text('[ERROR] File name does not exist.\r\n$ ', brush));
        return;
      }
      term.write(highlight.text('[INFO] Submitting file.\r\n$ ', brush));
      // Call the Deploy File interface to publish the file to the scheduling system
      const response = await services.ide.deployFile(workspace, source.key);
      if (response) {
        term.write(highlight.text('[INFO] Submit file success.\r\n$ ', brush));
      } else {
        term.write(highlight.text('[ERROR] Submit file failed.\r\n$ ', brush));
        return;
      }
      // Execute Smoke Test to run the scheduled task
      let dag: services.ide.Dag;
      try {
        term.write(highlight.text('[INFO] Start to run task.\r\n$ ', brush));
        dag = (await services.ide.runSmoke(workspace, file.nodeId, openPlatformBusinessName))[0];
        term.write(highlight.text('[INFO] Trigger sql task success.\r\n$ ', brush));
      } catch (e) {
        term.write(highlight.text('[ERROR] Trigger sql task failed.\r\n$ ', brush));
        return;
      }
      // Poll for Task Logs
      const event = setInterval(async () => {
        try {
          const logInfo = await services.ide.getLog(dag.instanceId, 'DEV');
          let log: string;
          switch (logInfo.instance.status) {
            case 'WAIT_TIME':
              log = 'Waiting for the scheduled time';
              break;
            case 'WAIT_RESOURCE':
              log = 'Waiting for resources...';
              break;
            default:
              log = logInfo.instanceLog;
          }
          term.write(`${highlight.text(log, brush).replace(/\n/g, '\r\n')}\r\n$ `);
          const finished = ['SUCCESS', 'FAILURE', 'NOT_RUN'].includes(logInfo.instance.status);
          finished && clearInterval(event);
        } catch (e) {
          term.write(highlight.text('[ERROR] SQL Task run failed.\r\n$ ', brush));
          return;
        }
      }, 3000);
    }

Local Deployment and Execution

Follow the Github code example to prepare the environment. Required tools include Java 8+, Maven, Node.js, and pnpm. Then, install dependencies:

pnpm install

Update the AccessKey ID (AK) and AccessKey Secret (SK) in the configuration. Finally, execute the sample code from the project root:

npm run example:ide

Once complete, visit the following URL to verify the results.

https://localhost:8080

Reference: Full Source Code

Download the full source code from Github code example. The complete process code is provided below.

import { useEffect, useRef, useState, useCallback } from 'react';
import type { FunctionComponent } from 'react';
import cn from 'classnames';
import * as monaco from 'monaco-editor';
import { Terminal } from 'xterm';
import { FitAddon } from 'xterm-addon-fit';
import { Tree, Select, Message } from '@alifd/next';
import * as highlight from '../helpers/highlight';
import * as services from '../services';
import classes from '../styles/app.module.css';

export interface Props {}
export interface NextTerminal extends Terminal {
  inputText?: string;
  stack: string[];
  pointer: number;
}

const brush = {
  rules: [
    { regex: /\bERROR\b/gmi, theme: 'red' },
    { regex: /\bWARN\b/gmi, theme: 'yellow' },
    { regex: /\bINFO\b/gmi, theme: 'green' },
    { regex: /^FAILED:.*$/gmi, theme: 'red' },
  ],
};
// Example Workflow name
const openPlatformBusinessName = 'Open Platform Example Workflow';
// Editor creation parameters
const editorOptions = {
  content: '',
  language: 'sql',
  theme: 'vs-dark',
  automaticLayout: true,
  fontSize: 16,
};
// Terminal creation parameters
const terminalOptions = {
  cursorBlink: true,
  cursorStyle: 'underline' as const,
  fontSize: 16,
};
const validCommands = [
  'run',
];

/**
 * Method to display Error Message popup
 * @param message Error message
 */
function showError(message: string) {
  Message.error({ title: 'Error Message', content: message });
}
/**
 * Method to display Tips popup
 * @param message Tips
 */
function showTips(message: string) {
  Message.show({ title: 'Tips', content: message });
}
/**
 * Method to handle task submission, triggered when "dw run ..." is entered in the terminal
 * @param term Terminal instance
 * @param dataSource Directory tree data source
 * @param workspace Workspace ID
 */
async function commandHandler(term: NextTerminal, dataSource: any, workspace?: number) {
  term.write('\r\n$ ');
  const input = term.inputText;
  term.inputText = '';
  if (['', undefined].includes(input)) {
    return;
  }
  term.stack = [input!, ...term.stack];
  term.pointer = -1;
  if (!workspace) {
    term.write(highlight.text('[ERROR] You should select workspace first.\r\n$ ', brush));
    return;
  }
  // Simple parsing of the input command line. If the command starts with "dw" and the execution command is "run", proceed; otherwise, report an error
  const words = input?.split(' ');
  const tag = words?.[0].toLowerCase();
  const command = words?.[1]?.toLowerCase();
  const fileName = words?.[2];
  if (tag !== 'dw' || !validCommands.includes(command!)) {
    term.write(highlight.text('[ERROR] Invalid command.\r\n$ ', brush));
    return;
  }
  // Get input file
  const source = dataSource?.[0]?.children.find((i: any) => i.label === fileName);
  const file = await services.ide.getFile(workspace, source.key);
  if (!file) {
    term.write(highlight.text('[ERROR] File name does not exist.\r\n$ ', brush));
    return;
  }
  term.write(highlight.text('[INFO] Submitting file.\r\n$ ', brush));
  // Call the Deploy File interface to publish the file to the scheduling system
  const response = await services.ide.deployFile(workspace, source.key);
  if (response) {
    term.write(highlight.text('[INFO] Submit file success.\r\n$ ', brush));
  } else {
    term.write(highlight.text('[ERROR] Submit file failed.\r\n$ ', brush));
    return;
  }
  // Execute Smoke Test to run the scheduled task
  let dag: services.ide.Dag;
  try {
    term.write(highlight.text('[INFO] Start to run task.\r\n$ ', brush));
    dag = (await services.ide.runSmoke(workspace, file.nodeId, openPlatformBusinessName))[0];
    term.write(highlight.text('[INFO] Trigger sql task success.\r\n$ ', brush));
  } catch (e) {
    term.write(highlight.text('[ERROR] Trigger sql task failed.\r\n$ ', brush));
    return;
  }
  // Poll for Task Logs
  const event = setInterval(async () => {
    try {
      const logInfo = await services.ide.getLog(dag.instanceId, 'DEV');
      let log: string;
      switch (logInfo.instance.status) {
        case 'WAIT_TIME':
          log = 'Waiting for the scheduled time';
          break;
        case 'WAIT_RESOURCE':
          log = 'Waiting for resources...';
          break;
        default:
          log = logInfo.instanceLog;
      }
      term.write(`${highlight.text(log, brush).replace(/\n/g, '\r\n')}\r\n$ `);
      const finished = ['SUCCESS', 'FAILURE', 'NOT_RUN'].includes(logInfo.instance.status);
      finished && clearInterval(event);
    } catch (e) {
      term.write(highlight.text('[ERROR] SQL Task run failed.\r\n$ ', brush));
      return;
    }
  }, 3000);
}
/**
 * Handle Terminal keyboard events
 * @param e Event object
 * @param term Terminal instance
 * @param dataSource Directory tree data source
 * @param workspace Workspace ID
 */
function onTerminalKeyChange(e: { key: string; domEvent: KeyboardEvent; }, term: NextTerminal, dataSource: any, workspace?: number) {
  const ev = e.domEvent;
  const printable = !ev.altKey && !ev.ctrlKey && !ev.metaKey;
  term.inputText = typeof term.inputText === 'string' ? term.inputText : '';
  switch (ev.key) {
    case 'ArrowUp':
      term.pointer = term.pointer < (term.stack.length - 1) ? term.pointer + 1 : term.pointer;
      term.inputText = term.stack[term.pointer];
      term.write(`\x1b[2K\r$ ${term.inputText}`);
      break;
    case 'ArrowDown':
      term.pointer = term.pointer > -1 ? term.pointer - 1 : -1;
      term.inputText = term.pointer === -1 ? '' : term.stack[term.pointer];
      term.write(`\x1b[2K\r$ ${term.inputText}`);
      break;
    case 'ArrowLeft':
      (term as any)._core.buffer.x > 2 && printable && term.write(e.key);
      break;
    case 'ArrowRight':
      (term as any)._core.buffer.x <= (term.inputText.length + 1) && printable && term.write(e.key);
      break;
    case 'Enter':
      commandHandler(term, dataSource, workspace);
      break;
    case 'Backspace':
      if ((term as any)._core.buffer.x > 2) {
        term.inputText = term.inputText.slice(0, -1);
        term.write('\b \b');
      }
      break;
    default:
      if (printable) {
        term.inputText += e.key;
        term.write(e.key);
      }
  }
}
/**
 * Get Workspace list
 */
async function getWorkspaceList() {
  const response = await services.tenant.getProjectList();
  const list = response.projectList.filter(i => i.projectStatusCode === 'AVAILABLE').map(i => (
    { label: i.projectName, value: i.projectId }
  ));
  return list;
}
/**
 * Get directory tree data source
 * @param workspace Workspace ID
 * @param dataSource Workspace list
 */
async function getTreeDataSource(workspace: number, dataSource: { label: string, value: number }[]) {
  try {
    const businesses = await services.ide.getBusinessList(workspace, openPlatformBusinessName);
    businesses.length === 0 && await services.ide.createBusiness(workspace, openPlatformBusinessName);
  } catch (e) {
    showError('You have no permission to access this workspace.');
    return;
  }
  const fileFolderPath = `Workflow/${openPlatformBusinessName}/MaxCompute`;
  const files = await services.ide.getFileList(workspace, fileFolderPath);
  let children: { key: number, label: string }[] = [];
  if (files.length === 0) {
    try {
      const currentWorkspace = dataSource.find(i => i.value === workspace);
      const file1 = await services.ide.createFile(workspace, currentWorkspace!.label, fileFolderPath, 'simpleSQL.mc.sql', 'SELECT 1');
      const file2 = await services.ide.createFile(workspace, currentWorkspace!.label, fileFolderPath, 'createTable.mc.sql', 'CREATE TABLE IF NOT EXISTS _qcc_mysql1_odps_source_20220113100903_done_ (\ncol string\n)\nCOMMENT \'Table indicating full data synchronization is DONE\'\nPARTITIONED BY\n(\nstatus STRING   COMMENT \'Partition indicating DONE\'\n)\nLIFECYCLE 36500;');
      children = children.concat([
        { key: file1, label: 'simpleSQL.mc.sql' },
        { key: file2, label: 'createTable.mc.sql' },
      ]);
    } catch (e) {
      showError('Create file failed. The datasource odps_source does not exist.');
      return;
    }
  } else {
    children = files.map((i) => ({ key: i.fileId, label: i.fileName }));
  }
  return [{ key: 1, label: openPlatformBusinessName, children }];
}
/**
 * Get file details
 * @param workspace Workspace ID
 * @param fileId File ID
 */
async function getFileInfo(workspace: number, fileId: number) {
  const response = await services.ide.getFile(workspace, fileId);
  return response;
}
/**
 * Save file, triggered by Ctrl+S
 * @param workspace Workspace ID
 * @param editor Editor instance
 * @param selectedFile Selected file
 */
async function saveFile(workspace: number, editor: monaco.editor.IStandaloneCodeEditor, selectedFile?: number) {
  if (!selectedFile) {
    showTips('Please select a file.');
    return;
  }
  const content = editor.getValue();
  const result = await services.ide.updateFile(workspace, selectedFile, { content });
  result ? showTips('Saved file') : showError('Failed to save file');
}

const App: FunctionComponent<Props> = () => {
  const editorRef = useRef<HTMLDivElement>(null);
  const termianlRef = useRef<HTMLDivElement>(null);
  const [terminal, setTerminal] = useState<NextTerminal>();
  const [editor, setEditor] = useState<monaco.editor.IStandaloneCodeEditor>();
  const [expnadedKeys, setExpandedKeys] = useState<any[]>();
  const [workspace, setWorkspace] = useState<number>();
  const [workspaces, setWorkspaces] = useState<{ label: string, value: number }[]>([]);
  const [dataSource, setDataSource] = useState<any[]>();
  const [selectedFile, setSelectedFile] = useState<number>();
  const [loading, setLoading] = useState<boolean>(false);
  // Create editor instance
  useEffect(() => {
    if (editorRef.current) {
      const nextEditor = monaco.editor.create(editorRef.current, editorOptions);
      setEditor(nextEditor);
      return () => { nextEditor.dispose(); };
    }
  }, [editorRef.current]);
  // Add key event for saving file
  useEffect(() => {
    editor?.addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyS, () => {
      if (!workspace) {
        showTips('Please select workspace first');
        return;
      }
      saveFile(workspace, editor, selectedFile);
    });
  }, [editor, workspace, selectedFile]);
  // Create terminal instance
  useEffect(() => {
    if (termianlRef.current) {
      const term: NextTerminal = new Terminal(terminalOptions) as any;
      term.pointer = -1;
      term.stack = [];
      setTerminal(term);
      const fitAddon = new FitAddon();
      term.loadAddon(fitAddon);
      term.open(termianlRef.current);
      fitAddon.fit();
      term.write('$ ');
      return () => { term.dispose(); };
    }
  }, [termianlRef.current]);
  // Register terminal input event
  useEffect(() => {
    const event = terminal?.onKey(e => onTerminalKeyChange(e, terminal, dataSource, workspace));
    return () => {
      event?.dispose();
    };
  }, [terminal, dataSource, workspace]);
  // Get directory tree data source
  useEffect(() => {
    workspace && (async () => {
      setLoading(true);
      const nextDataSource = await getTreeDataSource(workspace, workspaces);
      const defaultKey = nextDataSource?.[0]?.key;
      defaultKey && setExpandedKeys([defaultKey]);
      setDataSource(nextDataSource);
      setLoading(false);
    })();
  }, [workspace]);
  // When a file in the directory tree is clicked, get file details and display code
  useEffect(() => {
    workspace && selectedFile && (async () => {
      setLoading(true);
      const file = await getFileInfo(workspace, selectedFile);
      editor?.setValue(file.content);
      editor?.getAction('editor.action.formatDocument').run();
      setLoading(false);
    })();
  }, [selectedFile]);
  // Get Workspace list
  useEffect(() => {
    (async () => {
      const list = await getWorkspaceList();
      setWorkspaces(list);
    })();
  }, []);
  const onExapnd = useCallback((keys: number[]) => { setExpandedKeys(keys); }, []);
  const onWorkspaceChange = useCallback((value: number) => { setWorkspace(value) }, []);
  const onTreeNodeSelect = useCallback((key: number[]) => { key[0] && setSelectedFile(key[0]) }, []);
  return (
    <div className={cn(classes.appWrapper)}>
      <div className={cn(classes.leftArea)}>
        <div className={cn(classes.workspaceWrapper)}>
          Workspace:
          <Select
            value={workspace}
            dataSource={workspaces}
            onChange={onWorkspaceChange}
            autoWidth={false}
            showSearch
          />
        </div>
        <div className={cn(classes.treeWrapper)}>
          <Tree
            dataSource={dataSource}
            isNodeBlock={{ defaultPaddingLeft: 20 }}
            expandedKeys={expnadedKeys}
            selectedKeys={[selectedFile]}
            onExpand={onExapnd}
            onSelect={onTreeNodeSelect}
            defaultExpandAll
          />
        </div>
      </div>
      <div className={cn(classes.rightArea)}>
        <div
          className={cn(classes.monacoEditorWrapper)}
          ref={editorRef}
        />
        <div
          className={cn(classes.panelWrapper)}
          ref={termianlRef}
        />
      </div>
      <div className={cn(classes.loaderLine)} style={{ display: loading ? 'block' : 'none' }} />
    </div>
  );
};

export default App;