Contoh Step Functions yang digunakan SDK untuk Kotlin - AWS SDKContoh Kode

Ada lebih banyak AWS SDK contoh yang tersedia di GitHub repo SDKContoh AWS Dokumen.

Terjemahan disediakan oleh mesin penerjemah. Jika konten terjemahan yang diberikan bertentangan dengan versi bahasa Inggris aslinya, utamakan versi bahasa Inggris.

Contoh Step Functions yang digunakan SDK untuk Kotlin

Contoh kode berikut menunjukkan cara melakukan tindakan dan mengimplementasikan skenario umum dengan menggunakan AWS SDK for Kotlin with Step Functions.

Dasar-dasar adalah contoh kode yang menunjukkan kepada Anda bagaimana melakukan operasi penting dalam suatu layanan.

Tindakan adalah kutipan kode dari program yang lebih besar dan harus dijalankan dalam konteks. Sementara tindakan menunjukkan cara memanggil fungsi layanan individual, Anda dapat melihat tindakan dalam konteks dalam skenario terkait.

Setiap contoh menyertakan tautan ke kode sumber lengkap, di mana Anda dapat menemukan instruksi tentang cara mengatur dan menjalankan kode dalam konteks.

Memulai

Contoh kode berikut menunjukkan cara memulai menggunakan Step Functions.

SDKuntuk Kotlin
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode AWS.

import aws.sdk.kotlin.services.sfn.SfnClient import aws.sdk.kotlin.services.sfn.model.ListStateMachinesRequest /** Before running this Kotlin code example, set up your development environment, including your credentials. For more information, see the following documentation topic: https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup.html */ suspend fun main() { println(DASHES) println("Welcome to the AWS Step Functions Hello example.") println("Lets list up to ten of your state machines:") println(DASHES) listMachines() } suspend fun listMachines() { SfnClient { region = "us-east-1" }.use { sfnClient -> val response = sfnClient.listStateMachines(ListStateMachinesRequest {}) response.stateMachines?.forEach { machine -> println("The name of the state machine is ${machine.name}") println("The ARN value is ${machine.stateMachineArn}") } } }

Hal-hal mendasar

Contoh kode berikut ini menunjukkan cara:

  • Buat aktivitas.

  • Buat mesin status dari definisi Bahasa Negara Amazon yang berisi aktivitas yang dibuat sebelumnya sebagai langkah.

  • Jalankan mesin status dan tanggapi aktivitas dengan input pengguna.

  • Dapatkan status dan output akhir setelah proses selesai, lalu bersihkan sumber daya.

SDKuntuk Kotlin
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode AWS.

import aws.sdk.kotlin.services.iam.IamClient import aws.sdk.kotlin.services.iam.model.CreateRoleRequest import aws.sdk.kotlin.services.sfn.SfnClient import aws.sdk.kotlin.services.sfn.model.CreateActivityRequest import aws.sdk.kotlin.services.sfn.model.CreateStateMachineRequest import aws.sdk.kotlin.services.sfn.model.DeleteActivityRequest import aws.sdk.kotlin.services.sfn.model.DeleteStateMachineRequest import aws.sdk.kotlin.services.sfn.model.DescribeExecutionRequest import aws.sdk.kotlin.services.sfn.model.DescribeStateMachineRequest import aws.sdk.kotlin.services.sfn.model.GetActivityTaskRequest import aws.sdk.kotlin.services.sfn.model.ListActivitiesRequest import aws.sdk.kotlin.services.sfn.model.ListStateMachinesRequest import aws.sdk.kotlin.services.sfn.model.SendTaskSuccessRequest import aws.sdk.kotlin.services.sfn.model.StartExecutionRequest import aws.sdk.kotlin.services.sfn.model.StateMachineType import aws.sdk.kotlin.services.sfn.paginators.listActivitiesPaginated import aws.sdk.kotlin.services.sfn.paginators.listStateMachinesPaginated import com.fasterxml.jackson.databind.JsonNode import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.databind.node.ObjectNode import kotlinx.coroutines.flow.transform import java.util.Scanner import java.util.UUID import kotlin.collections.ArrayList import kotlin.system.exitProcess /** To run this code example, place the chat_sfn_state_machine.json file into your project's resources folder. You can obtain the JSON file to create a state machine in the following GitHub location: https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/resources/sample_files Before running this Kotlin code example, set up your development environment, including your credentials. For more information, see the following documentation topic: https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup.html This Kotlin code example performs the following tasks: 1. List activities using a paginator. 2. List state machines using a paginator. 3. Creates an activity. 4. Creates a state machine. 5. Describes the state machine. 6. Starts execution of the state machine and interacts with it. 7. Describes the execution. 8. Deletes the activity. 9. Deletes the state machine. */ val DASHES: String = String(CharArray(80)).replace("\u0000", "-") suspend fun main(args: Array<String>) { val usage = """ Usage: <roleARN> <activityName> <stateMachineName> Where: roleName - The name of the IAM role to create for this state machine. activityName - The name of an activity to create. stateMachineName - The name of the state machine to create. """ if (args.size != 3) { println(usage) exitProcess(0) } val roleName = args[0] val activityName = args[1] val stateMachineName = args[2] val sc = Scanner(System.`in`) var action = false val polJSON = """{ "Version": "2012-10-17", "Statement": [ { "Sid": "", "Effect": "Allow", "Principal": { "Service": "states.amazonaws.com" }, "Action": "sts:AssumeRole" } ] }""" println(DASHES) println("Welcome to the AWS Step Functions example scenario.") println(DASHES) println(DASHES) println("1. List activities using a Paginator.") listActivitesPagnator() println(DASHES) println(DASHES) println("2. List state machines using a paginator.") listStatemachinesPagnator() println(DASHES) println(DASHES) println("3. Create a new activity.") val activityArn = createActivity(activityName) println("The ARN of the Activity is $activityArn") println(DASHES) // Get JSON to use for the state machine and place the activityArn value into it. val stream = GetStream() val jsonString = stream.getStream() // Modify the Resource node. val objectMapper = ObjectMapper() val root: JsonNode = objectMapper.readTree(jsonString) (root.path("States").path("GetInput") as ObjectNode).put("Resource", activityArn) // Convert the modified Java object back to a JSON string. val stateDefinition = objectMapper.writeValueAsString(root) println(stateDefinition) println(DASHES) println("4. Create a state machine.") val roleARN = createIAMRole(roleName, polJSON) val stateMachineArn = createMachine(roleARN, stateMachineName, stateDefinition) println("The ARN of the state machine is $stateMachineArn") println(DASHES) println(DASHES) println("5. Describe the state machine.") describeStateMachine(stateMachineArn) println("What should ChatSFN call you?") val userName = sc.nextLine() println("Hello $userName") println(DASHES) println(DASHES) // The JSON to pass to the StartExecution call. val executionJson = "{ \"name\" : \"$userName\" }" println(executionJson) println("6. Start execution of the state machine and interact with it.") val runArn = startWorkflow(stateMachineArn, executionJson) println("The ARN of the state machine execution is $runArn") var myList: List<String> while (!action) { myList = getActivityTask(activityArn) println("ChatSFN: " + myList[1]) println("$userName please specify a value.") val myAction = sc.nextLine() if (myAction.compareTo("done") == 0) { action = true } println("You have selected $myAction") val taskJson = "{ \"action\" : \"$myAction\" }" println(taskJson) sendTaskSuccess(myList[0], taskJson) } println(DASHES) println(DASHES) println("7. Describe the execution.") describeExe(runArn) println(DASHES) println(DASHES) println("8. Delete the activity.") deleteActivity(activityArn) println(DASHES) println(DASHES) println("9. Delete the state machines.") deleteMachine(stateMachineArn) println(DASHES) println(DASHES) println("The AWS Step Functions example scenario is complete.") println(DASHES) } suspend fun listStatemachinesPagnator() { val machineRequest = ListStateMachinesRequest { maxResults = 10 } SfnClient { region = "us-east-1" }.use { sfnClient -> sfnClient .listStateMachinesPaginated(machineRequest) .transform { it.stateMachines?.forEach { obj -> emit(obj) } } .collect { obj -> println(" The state machine ARN is ${obj.stateMachineArn}") } } } suspend fun listActivitesPagnator() { val activitiesRequest = ListActivitiesRequest { maxResults = 10 } SfnClient { region = "us-east-1" }.use { sfnClient -> sfnClient .listActivitiesPaginated(activitiesRequest) .transform { it.activities?.forEach { obj -> emit(obj) } } .collect { obj -> println(" The activity ARN is ${obj.activityArn}") } } } suspend fun deleteMachine(stateMachineArnVal: String?) { val deleteStateMachineRequest = DeleteStateMachineRequest { stateMachineArn = stateMachineArnVal } SfnClient { region = "us-east-1" }.use { sfnClient -> sfnClient.deleteStateMachine(deleteStateMachineRequest) println("$stateMachineArnVal was successfully deleted.") } } suspend fun deleteActivity(actArn: String?) { val activityRequest = DeleteActivityRequest { activityArn = actArn } SfnClient { region = "us-east-1" }.use { sfnClient -> sfnClient.deleteActivity(activityRequest) println("You have deleted $actArn") } } suspend fun describeExe(executionArnVal: String?) { val executionRequest = DescribeExecutionRequest { executionArn = executionArnVal } var status = "" var hasSucceeded = false while (!hasSucceeded) { SfnClient { region = "us-east-1" }.use { sfnClient -> val response = sfnClient.describeExecution(executionRequest) status = response.status.toString() if (status.compareTo("RUNNING") == 0) { println("The state machine is still running, let's wait for it to finish.") Thread.sleep(2000) } else if (status.compareTo("SUCCEEDED") == 0) { println("The Step Function workflow has succeeded") hasSucceeded = true } else { println("The Status is neither running or succeeded") } } } println("The Status is $status") } suspend fun sendTaskSuccess( token: String?, json: String?, ) { val successRequest = SendTaskSuccessRequest { taskToken = token output = json } SfnClient { region = "us-east-1" }.use { sfnClient -> sfnClient.sendTaskSuccess(successRequest) } } suspend fun getActivityTask(actArn: String?): List<String> { val myList: MutableList<String> = ArrayList() val getActivityTaskRequest = GetActivityTaskRequest { activityArn = actArn } SfnClient { region = "us-east-1" }.use { sfnClient -> val response = sfnClient.getActivityTask(getActivityTaskRequest) myList.add(response.taskToken.toString()) myList.add(response.input.toString()) return myList } } suspend fun startWorkflow( stateMachineArnVal: String?, jsonEx: String?, ): String? { val uuid = UUID.randomUUID() val uuidValue = uuid.toString() val executionRequest = StartExecutionRequest { input = jsonEx stateMachineArn = stateMachineArnVal name = uuidValue } SfnClient { region = "us-east-1" }.use { sfnClient -> val response = sfnClient.startExecution(executionRequest) return response.executionArn } } suspend fun describeStateMachine(stateMachineArnVal: String?) { val stateMachineRequest = DescribeStateMachineRequest { stateMachineArn = stateMachineArnVal } SfnClient { region = "us-east-1" }.use { sfnClient -> val response = sfnClient.describeStateMachine(stateMachineRequest) println("The name of the State machine is ${response.name}") println("The status of the State machine is ${response.status}") println("The ARN value of the State machine is ${response.stateMachineArn}") println("The role ARN value is ${response.roleArn}") } } suspend fun createMachine( roleARNVal: String?, stateMachineName: String?, jsonVal: String?, ): String? { val machineRequest = CreateStateMachineRequest { definition = jsonVal name = stateMachineName roleArn = roleARNVal type = StateMachineType.Standard } SfnClient { region = "us-east-1" }.use { sfnClient -> val response = sfnClient.createStateMachine(machineRequest) return response.stateMachineArn } } suspend fun createIAMRole( roleNameVal: String?, polJSON: String?, ): String? { val request = CreateRoleRequest { roleName = roleNameVal assumeRolePolicyDocument = polJSON description = "Created using the AWS SDK for Kotlin" } IamClient { region = "AWS_GLOBAL" }.use { iamClient -> val response = iamClient.createRole(request) return response.role?.arn } } suspend fun createActivity(activityName: String): String? { val activityRequest = CreateActivityRequest { name = activityName } SfnClient { region = "us-east-1" }.use { sfnClient -> val response = sfnClient.createActivity(activityRequest) return response.activityArn } }

Tindakan

Contoh kode berikut menunjukkan cara menggunakanCreateActivity.

SDKuntuk Kotlin
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode AWS.

suspend fun createActivity(activityName: String): String? { val activityRequest = CreateActivityRequest { name = activityName } SfnClient { region = "us-east-1" }.use { sfnClient -> val response = sfnClient.createActivity(activityRequest) return response.activityArn } }

Contoh kode berikut menunjukkan cara menggunakanCreateStateMachine.

SDKuntuk Kotlin
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode AWS.

suspend fun createMachine( roleARNVal: String?, stateMachineName: String?, jsonVal: String?, ): String? { val machineRequest = CreateStateMachineRequest { definition = jsonVal name = stateMachineName roleArn = roleARNVal type = StateMachineType.Standard } SfnClient { region = "us-east-1" }.use { sfnClient -> val response = sfnClient.createStateMachine(machineRequest) return response.stateMachineArn } }

Contoh kode berikut menunjukkan cara menggunakanDeleteActivity.

SDKuntuk Kotlin
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode AWS.

suspend fun deleteActivity(actArn: String?) { val activityRequest = DeleteActivityRequest { activityArn = actArn } SfnClient { region = "us-east-1" }.use { sfnClient -> sfnClient.deleteActivity(activityRequest) println("You have deleted $actArn") } }

Contoh kode berikut menunjukkan cara menggunakanDeleteStateMachine.

SDKuntuk Kotlin
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode AWS.

suspend fun deleteMachine(stateMachineArnVal: String?) { val deleteStateMachineRequest = DeleteStateMachineRequest { stateMachineArn = stateMachineArnVal } SfnClient { region = "us-east-1" }.use { sfnClient -> sfnClient.deleteStateMachine(deleteStateMachineRequest) println("$stateMachineArnVal was successfully deleted.") } }

Contoh kode berikut menunjukkan cara menggunakanDescribeExecution.

SDKuntuk Kotlin
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode AWS.

suspend fun describeExe(executionArnVal: String?) { val executionRequest = DescribeExecutionRequest { executionArn = executionArnVal } var status = "" var hasSucceeded = false while (!hasSucceeded) { SfnClient { region = "us-east-1" }.use { sfnClient -> val response = sfnClient.describeExecution(executionRequest) status = response.status.toString() if (status.compareTo("RUNNING") == 0) { println("The state machine is still running, let's wait for it to finish.") Thread.sleep(2000) } else if (status.compareTo("SUCCEEDED") == 0) { println("The Step Function workflow has succeeded") hasSucceeded = true } else { println("The Status is neither running or succeeded") } } } println("The Status is $status") }

Contoh kode berikut menunjukkan cara menggunakanDescribeStateMachine.

SDKuntuk Kotlin
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode AWS.

suspend fun describeStateMachine(stateMachineArnVal: String?) { val stateMachineRequest = DescribeStateMachineRequest { stateMachineArn = stateMachineArnVal } SfnClient { region = "us-east-1" }.use { sfnClient -> val response = sfnClient.describeStateMachine(stateMachineRequest) println("The name of the State machine is ${response.name}") println("The status of the State machine is ${response.status}") println("The ARN value of the State machine is ${response.stateMachineArn}") println("The role ARN value is ${response.roleArn}") } }

Contoh kode berikut menunjukkan cara menggunakanGetActivityTask.

SDKuntuk Kotlin
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode AWS.

suspend fun getActivityTask(actArn: String?): List<String> { val myList: MutableList<String> = ArrayList() val getActivityTaskRequest = GetActivityTaskRequest { activityArn = actArn } SfnClient { region = "us-east-1" }.use { sfnClient -> val response = sfnClient.getActivityTask(getActivityTaskRequest) myList.add(response.taskToken.toString()) myList.add(response.input.toString()) return myList } }

Contoh kode berikut menunjukkan cara menggunakanListActivities.

SDKuntuk Kotlin
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode AWS.

suspend fun listAllActivites() { val activitiesRequest = ListActivitiesRequest { maxResults = 10 } SfnClient { region = "us-east-1" }.use { sfnClient -> val response = sfnClient.listActivities(activitiesRequest) response.activities?.forEach { item -> println("The activity ARN is ${item.activityArn}") println("The activity name is ${item.name}") } } }

Contoh kode berikut menunjukkan cara menggunakanListExecutions.

SDKuntuk Kotlin
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode AWS.

suspend fun getExeHistory(exeARN: String?) { val historyRequest = GetExecutionHistoryRequest { executionArn = exeARN maxResults = 10 } SfnClient { region = "us-east-1" }.use { sfnClient -> val response = sfnClient.getExecutionHistory(historyRequest) response.events?.forEach { event -> println("The event type is ${event.type}") } } }

Contoh kode berikut menunjukkan cara menggunakanListStateMachines.

SDKuntuk Kotlin
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode AWS.

import aws.sdk.kotlin.services.sfn.SfnClient import aws.sdk.kotlin.services.sfn.model.ListStateMachinesRequest /** Before running this Kotlin code example, set up your development environment, including your credentials. For more information, see the following documentation topic: https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup.html */ suspend fun main() { println(DASHES) println("Welcome to the AWS Step Functions Hello example.") println("Lets list up to ten of your state machines:") println(DASHES) listMachines() } suspend fun listMachines() { SfnClient { region = "us-east-1" }.use { sfnClient -> val response = sfnClient.listStateMachines(ListStateMachinesRequest {}) response.stateMachines?.forEach { machine -> println("The name of the state machine is ${machine.name}") println("The ARN value is ${machine.stateMachineArn}") } } }

Contoh kode berikut menunjukkan cara menggunakanSendTaskSuccess.

SDKuntuk Kotlin
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode AWS.

suspend fun sendTaskSuccess( token: String?, json: String?, ) { val successRequest = SendTaskSuccessRequest { taskToken = token output = json } SfnClient { region = "us-east-1" }.use { sfnClient -> sfnClient.sendTaskSuccess(successRequest) } }

Contoh kode berikut menunjukkan cara menggunakanStartExecution.

SDKuntuk Kotlin
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode AWS.

suspend fun startWorkflow( stateMachineArnVal: String?, jsonEx: String?, ): String? { val uuid = UUID.randomUUID() val uuidValue = uuid.toString() val executionRequest = StartExecutionRequest { input = jsonEx stateMachineArn = stateMachineArnVal name = uuidValue } SfnClient { region = "us-east-1" }.use { sfnClient -> val response = sfnClient.startExecution(executionRequest) return response.executionArn } }