aertje / cloud-tasks-emulator

Google cloud tasks emulator

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

[Java Example] How to get the Java CloudTasksClient pointed at the emulator

ScottPierce opened this issue · comments

I just spent a good bit of time figuring out how to get the Java client working with the emulator. I thought it was worth recording a working example somewhere in case someone else searches for an example, as I found no Java examples for this project.

The following code is Kotlin, but it's using the Java Cloud Tasks library, and the syntax differences from Java are minor:

val client = CloudTasksClient.create(
    CloudTasksSettings.newBuilder()
        .setCredentialsProvider(NoCredentialsProvider.create())
        .setTransportChannelProvider(
            InstantiatingGrpcChannelProvider.newBuilder()
                .setEndpoint("localhost:8123")
                .setChannelConfigurator { obj: ManagedChannelBuilder<*>? -> obj!!.usePlaintext() }
                .build()
        )
        .build()
)

You can close this ticket. Thanks for maintaining this emulator for the community :)

Hey Scott, cheers for that - I'll probably make it into Java and add it when I get a chance.

public static void createQueue(String projectId, String locationId, String queueId) {
    try (var client = CloudTasksClient.create(
            CloudTasksSettings.newBuilder()
                    .setCredentialsProvider(NoCredentialsProvider.create())
                    .setTransportChannelProvider(
                            InstantiatingGrpcChannelProvider.newBuilder()
                                    .setEndpoint("localhost:8123")
                                    .setChannelConfigurator(ManagedChannelBuilder::usePlaintext)
                                    .build())
                    .build())) {

        String parent = LocationName.of(projectId, locationId).toString();
        String queuePath = QueueName.of(projectId, locationId, queueId).toString();

        Queue queue = client.createQueue(parent, Queue.newBuilder().setName(queuePath).build());
        System.out.println("Queue created: " + queue.getName());

    } catch (IOException e) {
        System.out.println("Error creating queue: " + e.getMessage());
    }
}

If someone looking for Java Code. , Any one tried with OidcToken while creating task ?