GithubHelp home page GithubHelp logo

kotlin-samples's Introduction

Google Cloud Platform Kotlin Samples

This repository holds samples written in Kotlin that demonstrate the Google Cloud Platform.

Index

Path Description
appengine Basic examples for deploying Kotlin applications to App Engine for Java 8.
firestore This sample demonstrates the Google Cloud Firestore API.
functions This sample demonstrates deploying to Google Cloud Functions.
pubsub This sample demonstrates the Google Cloud Pub/Sub API.
run Basic examples for deploying Kotlin applications to Cloud Run.
storage This sample demonstrates the Google Cloud Storage API.
vision This sample demonstrates the Google Cloud Vision API.
emojify Getting started with Server side Kotlin? This app demonstrates an Android frontend written in Kotlin that communicates with a Kotlin backend running on App Engine for Java 8.

The samples use the Google Cloud Client Library for Java.

Contributing changes.

Entirely new samples and bug fixes are welcome. See CONTRIBUTING.md for details on how to contribute.

Licensing

Code in this repository is licensed under the Apache 2.0. See LICENSE.

kotlin-samples's People

Contributors

arunsathiya avatar bshaffer avatar daviddenton avatar dependabot[bot] avatar github-actions[bot] avatar google-cloud-policy-bot[bot] avatar grant avatar handstandsam avatar iennae avatar jamesward avatar justinbeckwith avatar renovate-bot avatar renovate[bot] avatar surferjeffatgoogle avatar utgarda avatar vlsi avatar wisdal avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

kotlin-samples's Issues

Create a Kotlin sample for Google Cloud Storage

Let's create a simple sample for calling Google Cloud Storage from Kotlin. This sample exists for creating a bucket in Java.

The sample should demonstrate the following:

  • Create a bucket
  • Upload an object
  • Download an object

Use the vision sample for guidance. Command-line only is ok.

Not able to use the project to deploy kotlin project to cloud run

Expand all | Collapse all{
insertId: "5e54c1ae00030aa84bd7cf47"
labels: {
instanceId: "00bf4bf02d2112b83366440937a7f764ba2a4ef55eeb0ec7c4d2f58330367035d3db3321679ea9ba7e6e584cbec2525f6cd4cb90040c40eb13d621458f60c2"
}
logName: "projects/dummy-pos-certi2/logs/run.googleapis.com%2Fstderr"
receiveTimestamp: "2020-02-25T06:41:50.406969252Z"
resource: {
labels: {
configuration_name: "ssl-server"
location: "us-east1"
project_id: "dummy-pos-certi2"
revision_name: "ssl-server-00003-pog"
service_name: "ssl-server"
}
type: "cloud_run_revision"
}
textPayload: "Exception in thread "main" java.lang.NoClassDefFoundError: kotlin/jvm/internal/Intrinsics
at au.com.orient.MainKt.main(Main.kt)
Caused by: java.lang.ClassNotFoundException: kotlin.jvm.internal.Intrinsics
at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:349)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 1 more"
timestamp: "2020-02-25T06:41:50.199336Z"
}

Ktor AppEngine - An illegal reflective access operation has occurred

Running the code locally after cloning, I get this:

➜ steward ./gradlew appengineRun
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by com.google.appengine.tools.development.StreamHandlerFactory (file:/Users/rojepp/google-cloud-sdk/platform/google_appengine/google/appengine/tools/java/lib/impl/appengine-local-runtime.jar) to method java.net.URL.getURLStreamHandler(java.lang.String)
WARNING: Please consider reporting this to the maintainers of com.google.appengine.tools.development.StreamHandlerFactory
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release
java.lang.RuntimeException: Unable to create a DevAppServer
at com.google.appengine.tools.development.DevAppServerFactory.doCreateDevAppServer(DevAppServerFactory.java:369)
at com.google.appengine.tools.development.DevAppServerFactory.createDevAppServer(DevAppServerFactory.java:301)
at com.google.appengine.tools.development.DevAppServerMain$StartAction.apply(DevAppServerMain.java:383)
at com.google.appengine.tools.util.Parser$ParseResult.applyArgs(Parser.java:45)
at com.google.appengine.tools.development.DevAppServerMain.run(DevAppServerMain.java:257)
at com.google.appengine.tools.development.DevAppServerMain.main(DevAppServerMain.java:248)
Caused by: java.lang.ExceptionInInitializerError
at com.google.appengine.tools.development.DevAppServerImpl.(DevAppServerImpl.java:127)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:500)
at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:481)
at com.google.appengine.tools.development.DevAppServerFactory.doCreateDevAppServer(DevAppServerFactory.java:354)
... 5 more
Caused by: java.lang.IllegalStateException: java.lang.NoSuchMethodException: java.net.SocksSocketImpl.()
at com.google.appengine.tools.development.DevSocketImplFactory.(DevSocketImplFactory.java:76)
... 12 more
Caused by: java.lang.NoSuchMethodException: java.net.SocksSocketImpl.()
at java.base/java.lang.Class.getConstructor0(Class.java:3350)
at java.base/java.lang.Class.getDeclaredConstructor(Class.java:2554)
at com.google.appengine.tools.development.DevSocketImplFactory.(DevSocketImplFactory.java:72)

Add coroutines samples

I would like to have examples of how to integrate the different Google SDKs with coroutines (maybe in a Ktor application)

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.


⚠ Dependency Lookup Warnings ⚠

  • Renovate failed to look up the following dependencies: Failed to look up maven package com.google.cloud.tools.appengine:com.google.cloud.tools.appengine.gradle.plugin.

Files affected: appengine/ktor/build.gradle.kts


This repository currently has no open or pending branches.

Detected dependencies

github-actions
.github/workflows/generate_dependabot.yml
  • actions/checkout v4
  • peter-evans/create-pull-request v5
.github/workflows/gradle-wrapper-validation.yml
  • actions/checkout v4@8ade135a41bc03ea155e62e844d188df1ea18608
  • gradle/wrapper-validation-action v1
.github/workflows/lint.yml
  • actions/checkout v4@8ade135a41bc03ea155e62e844d188df1ea18608
.github/workflows/tests.yml
  • actions/checkout v4@8ade135a41bc03ea155e62e844d188df1ea18608
  • actions/checkout v4@8ade135a41bc03ea155e62e844d188df1ea18608
  • actions/setup-java v3
gradle
appengine/ktor/gradle.properties
appengine/ktor/settings.gradle.kts
appengine/ktor/build.gradle.kts
  • org.jetbrains.kotlin.jvm 1.9.10
  • com.google.cloud.tools.appengine 2.4.5
  • io.ktor:ktor-bom 2.3.5
  • io.ktor:ktor-server-call-logging 2.3.5
  • io.ktor:ktor-server-default-headers 2.3.5
  • com.google.cloud:google-cloud-logging-logback 0.130.23-alpha
  • com.google.appengine:appengine 1.9.98
firestore/settings.gradle.kts
  • org.gradle.toolchains.foojay-resolver-convention 0.7.0
firestore/build.gradle.kts
  • org.jetbrains.kotlin.jvm 1.9.10
  • com.google.cloud:google-cloud-firestore 3.14.4
  • junit:junit 4.13.2
functions/settings.gradle.kts
  • org.gradle.toolchains.foojay-resolver-convention 0.7.0
functions/build.gradle.kts
  • org.jetbrains.kotlin.jvm 1.9.10
  • com.github.johnrengelman.shadow 8.1.1
  • javax.servlet:javax.servlet-api 4.0.1
  • org.mockito:mockito-core 5.+
  • org.junit.jupiter:junit-jupiter-api 5.10.0
  • org.junit.jupiter:junit-jupiter-engine 5.10.0
getting-started/android-with-appengine/frontend/gradle.properties
getting-started/android-with-appengine/frontend/settings.gradle.kts
  • org.gradle.toolchains.foojay-resolver-convention 0.7.0
getting-started/android-with-appengine/frontend/build.gradle.kts
  • com.android.application 8.1.2
  • org.jetbrains.kotlin.android 1.9.10
getting-started/android-with-appengine/frontend/emojify/build.gradle.kts
  • androidx.constraintlayout:constraintlayout 2.1.4
  • com.yanzhenjie:album 2.1.3
  • com.yanzhenjie:mediascanner 1.0.3
  • com.google.android.material:material 1.10.0
  • androidx.appcompat:appcompat 1.6.1
  • androidx.recyclerview:recyclerview 1.3.1
  • androidx.cardview:cardview 1.0.0
  • com.github.bumptech.glide:glide 4.16.0
  • com.android.volley:volley 1.2.1
  • com.google.firebase:firebase-core 21.1.1
  • com.google.firebase:firebase-storage 20.2.1
  • com.google.firebase:firebase-auth 22.1.2
  • org.jetbrains.kotlinx:kotlinx-coroutines-core 1.7.3
pubsub/settings.gradle.kts
  • org.gradle.toolchains.foojay-resolver-convention 0.7.0
pubsub/build.gradle.kts
  • org.jetbrains.kotlin.jvm 1.9.10
  • com.github.johnrengelman.shadow 8.1.1
  • com.google.cloud:libraries-bom 26.24.0
  • org.jetbrains.kotlinx:kotlinx-coroutines-core 1.7.3
  • com.google.truth:truth 1.1.5
run/grpc-hello-world-bidi-streaming/settings.gradle.kts
  • org.gradle.toolchains.foojay-resolver-convention 0.7.0
run/grpc-hello-world-bidi-streaming/build.gradle.kts
  • org.jetbrains.kotlin.jvm 1.9.10
  • com.google.protobuf 0.9.4
  • org.jlleitschuh.gradle.ktlint 11.6.0
  • javax.annotation:javax.annotation-api 1.3.2
  • io.grpc:grpc-kotlin-stub 1.4.0
  • io.grpc:grpc-protobuf 1.58.0
  • com.google.protobuf:protobuf-kotlin 3.24.4
  • org.jetbrains.kotlinx:kotlinx-coroutines-core 1.7.3
  • io.grpc:grpc-netty-shaded 1.58.0
  • com.google.protobuf:protoc 3.24.4
  • io.grpc:protoc-gen-grpc-java 1.58.0
run/grpc-hello-world-gradle/settings.gradle.kts
  • org.gradle.toolchains.foojay-resolver-convention 0.7.0
run/grpc-hello-world-gradle/build.gradle.kts
  • org.jetbrains.kotlin.jvm 1.9.10
  • com.google.protobuf 0.9.4
  • org.jlleitschuh.gradle.ktlint 11.6.0
  • javax.annotation:javax.annotation-api 1.3.2
  • io.grpc:grpc-kotlin-stub 1.4.0
  • io.grpc:grpc-protobuf 1.58.0
  • com.google.protobuf:protobuf-kotlin 3.24.4
  • org.jetbrains.kotlinx:kotlinx-coroutines-core 1.7.3
  • io.grpc:grpc-netty-shaded 1.58.0
  • com.google.protobuf:protoc 3.24.4
  • io.grpc:protoc-gen-grpc-java 1.58.0
run/grpc-hello-world-streaming/settings.gradle.kts
  • org.gradle.toolchains.foojay-resolver-convention 0.7.0
run/grpc-hello-world-streaming/build.gradle.kts
  • org.jetbrains.kotlin.jvm 1.9.10
  • com.google.protobuf 0.9.4
  • org.jlleitschuh.gradle.ktlint 11.6.0
  • javax.annotation:javax.annotation-api 1.3.2
  • io.grpc:grpc-kotlin-stub 1.4.0
  • io.grpc:grpc-protobuf 1.58.0
  • com.google.protobuf:protobuf-kotlin 3.24.4
  • org.jetbrains.kotlinx:kotlinx-coroutines-core 1.7.3
  • io.grpc:grpc-netty-shaded 1.58.0
  • com.google.protobuf:protoc 3.24.4
  • io.grpc:protoc-gen-grpc-java 1.58.0
run/http4k-hello-world/settings.gradle.kts
  • org.gradle.toolchains.foojay-resolver-convention 0.7.0
run/http4k-hello-world/build.gradle.kts
  • org.jetbrains.kotlin.jvm 1.9.10
  • org.http4k:http4k-core 5.8.3.0
  • org.http4k:http4k-server-undertow 5.8.3.0
run/ktor-hello-world/settings.gradle.kts
  • org.gradle.toolchains.foojay-resolver-convention 0.7.0
run/ktor-hello-world/build.gradle.kts
  • org.jetbrains.kotlin.jvm 1.9.10
  • io.ktor:ktor-server-core 2.3.5
  • io.ktor:ktor-server-call-logging 2.3.5
  • io.ktor:ktor-server-default-headers 2.3.5
  • io.ktor:ktor-server-cio 2.3.5
  • ch.qos.logback:logback-classic 1.4.11
run/micronaut-hello-world/settings.gradle.kts
  • org.gradle.toolchains.foojay-resolver-convention 0.7.0
  • io.micronaut.platform.catalog 4.1.1
run/micronaut-hello-world/build.gradle.kts
  • org.jetbrains.kotlin.jvm 1.9.10
  • org.jetbrains.kotlin.plugin.allopen 1.9.10
  • com.google.devtools.ksp 1.9.10-1.0.13
  • io.micronaut.application 4.1.1
  • org.jetbrains.kotlinx:kotlinx-coroutines-core 1.7.3
run/micronaut-hello-world/gradle/libs.versions.toml
run/springboot-cloudsql/settings.gradle.kts
  • org.gradle.toolchains.foojay-resolver-convention 0.7.0
run/springboot-cloudsql/build.gradle.kts
  • org.jetbrains.kotlin.jvm 1.9.10
  • org.jetbrains.kotlin.plugin.spring 1.9.10
  • org.springframework.boot 3.1.4
  • io.spring.dependency-management 1.1.3
  • org.testcontainers:postgresql 1.19.1
  • org.testcontainers:r2dbc 1.19.1
run/springboot-hello-world/settings.gradle.kts
  • org.gradle.toolchains.foojay-resolver-convention 0.7.0
run/springboot-hello-world/build.gradle.kts
  • org.springframework.boot 3.1.4
  • io.spring.dependency-management 1.1.3
  • org.jetbrains.kotlin.jvm 1.9.10
  • org.jetbrains.kotlin.plugin.spring 1.9.10
storage/settings.gradle.kts
  • org.gradle.toolchains.foojay-resolver-convention 0.7.0
storage/build.gradle.kts
  • org.jetbrains.kotlin.jvm 1.9.10
  • com.google.cloud:google-cloud-storage 2.27.1
  • junit:junit 4.13.2
vision/settings.gradle.kts
  • org.gradle.toolchains.foojay-resolver-convention 0.7.0
vision/build.gradle.kts
  • org.jetbrains.kotlin.jvm 1.9.10
  • com.google.cloud:google-cloud-vision 3.22.0
  • junit:junit 4.13.2
gradle-wrapper
appengine/ktor/gradle/wrapper/gradle-wrapper.properties
  • gradle 8.4
firestore/gradle/wrapper/gradle-wrapper.properties
  • gradle 8.4
functions/gradle/wrapper/gradle-wrapper.properties
  • gradle 8.4
getting-started/android-with-appengine/frontend/gradle/wrapper/gradle-wrapper.properties
  • gradle 8.4
pubsub/gradle/wrapper/gradle-wrapper.properties
  • gradle 8.4
run/grpc-hello-world-bidi-streaming/gradle/wrapper/gradle-wrapper.properties
  • gradle 8.4
run/grpc-hello-world-gradle/gradle/wrapper/gradle-wrapper.properties
  • gradle 8.4
run/grpc-hello-world-streaming/gradle/wrapper/gradle-wrapper.properties
  • gradle 8.4
run/http4k-hello-world/gradle/wrapper/gradle-wrapper.properties
  • gradle 8.4
run/ktor-hello-world/gradle/wrapper/gradle-wrapper.properties
  • gradle 8.4
run/micronaut-hello-world/gradle/wrapper/gradle-wrapper.properties
  • gradle 8.4
run/springboot-cloudsql/gradle/wrapper/gradle-wrapper.properties
  • gradle 8.4
run/springboot-hello-world/gradle/wrapper/gradle-wrapper.properties
  • gradle 8.4
storage/gradle/wrapper/gradle-wrapper.properties
  • gradle 8.4
vision/gradle/wrapper/gradle-wrapper.properties
  • gradle 8.4
maven
appengine/springboot/pom.xml
  • org.springframework.boot:spring-boot-starter-parent 3.1.4
  • org.springframework.cloud:spring-cloud-dependencies 2022.0.4
  • com.google.cloud:spring-cloud-gcp-dependencies 4.8.1
  • com.google.cloud.tools:appengine-maven-plugin 2.5.0
  • org.jetbrains.kotlin:kotlin-maven-allopen 1.9.10
getting-started/android-with-appengine/backend/pom.xml
  • org.springframework.boot:spring-boot-starter-parent 3.1.4
  • com.google.cloud:libraries-bom 26.24.0
  • org.jetbrains.kotlin:kotlin-maven-allopen 1.9.10
  • com.google.cloud.tools:appengine-maven-plugin 2.5.0
run/grpc-hello-world-mvn/pom.xml
  • org.jetbrains.kotlin:kotlin-stdlib-jdk8 1.9.10
  • org.jetbrains.kotlinx:kotlinx-coroutines-core 1.7.3
  • javax.annotation:javax.annotation-api 1.3.2
  • io.grpc:grpc-kotlin-stub 1.4.0
  • io.grpc:grpc-stub 1.58.0
  • io.grpc:grpc-protobuf 1.58.0
  • com.google.protobuf:protobuf-java 3.24.4
  • com.google.protobuf:protobuf-kotlin 3.24.4
  • io.grpc:grpc-netty-shaded 1.58.0
  • kr.motd.maven:os-maven-plugin 1.7.1
  • org.xolstice.maven.plugins:protobuf-maven-plugin 0.6.1
  • io.grpc:protoc-gen-grpc-kotlin 1.4.0
  • org.jetbrains.kotlin:kotlin-maven-plugin 1.9.10
  • org.apache.maven.plugins:maven-compiler-plugin 3.11.0
  • org.codehaus.mojo:exec-maven-plugin 3.1.0
  • org.apache.maven.plugins:maven-dependency-plugin 3.6.0
  • com.github.gantsign.maven:ktlint-maven-plugin 3.0.0
run/plain-hello-world/pom.xml
  • org.jetbrains.kotlin:kotlin-stdlib-jdk8 1.9.10
  • org.jetbrains.kotlin:kotlin-maven-plugin 1.9.10
  • org.codehaus.mojo:exec-maven-plugin 3.1.0
  • com.google.cloud.tools:jib-maven-plugin 3.4.0
run/quarkus-hello-world/pom.xml
  • io.quarkus.platform:quarkus-bom 3.4.2
  • org.jetbrains.kotlin:kotlin-stdlib 1.9.10
  • io.quarkus.platform:quarkus-maven-plugin 3.4.2
  • org.apache.maven.plugins:maven-compiler-plugin 3.11.0
  • org.apache.maven.plugins:maven-surefire-plugin 3.1.2
  • org.jetbrains.kotlin:kotlin-maven-plugin 1.9.10
  • org.jetbrains.kotlin:kotlin-maven-allopen 1.9.10
maven-wrapper
appengine/springboot/.mvn/wrapper/maven-wrapper.properties
  • maven 3.9.5
  • maven-wrapper 3.2.0
getting-started/android-with-appengine/backend/.mvn/wrapper/maven-wrapper.properties
  • maven 3.9.5
  • maven-wrapper 3.2.0
run/grpc-hello-world-mvn/.mvn/wrapper/maven-wrapper.properties
  • maven 3.9.5
  • maven-wrapper 3.2.0
run/plain-hello-world/.mvn/wrapper/maven-wrapper.properties
  • maven 3.9.5
  • maven-wrapper 3.2.0
run/quarkus-hello-world/.mvn/wrapper/maven-wrapper.properties
  • maven 3.9.5
  • maven-wrapper 3.2.0

  • Check this box to trigger a request for Renovate to run again on this repository

ClassNotFoundException when running jar file

EDIT: Updated this with a more simplified example that should be much easier to debug.

I am trying to set up a pubsub POC with my current code (Kotlin) but we are not able to get the needed dependencies to run with it. I am following https://github.com/GoogleCloudPlatform/kotlin-samples/blob/master/pubsub/build.gradle as a guide. I am following the Gradle Kotlin DSL syntax for dependencies and I have added the dependencies to the build.gradle.kts, which now looks like this:

import org.jetbrains.kotlin.gradle.tasks.KotlinCompile

application {
    mainClassName = "MainKt"
}

plugins {
    kotlin("jvm") version "1.4.0"
    application
}
group = "testinpubsublib"
version = "0.9.0"

repositories {
    mavenCentral()
    jcenter()
}
dependencies {
    implementation(platform("com.google.cloud:libraries-bom:20.4.0"))
    implementation("com.google.cloud:google-cloud-pubsub")
}

tasks.jar {
    // names the jar app.jar
    archiveFileName.set("gcppubsubtest.jar")
    manifest {
        // helps make the jar executable by telling where the entry method is
        attributes["Main-Class"] = "MainKt"
    }

    // adds all deps into the jar making it a "fat jar", runable on its own
    from { configurations.runtimeClasspath.get().map { if (it.isDirectory) it else zipTree(it) } }
}

tasks.withType<KotlinCompile>() {
    kotlinOptions.jvmTarget = "14"
}

The app is a very basic hello world app:

fun main(args: Array<String>) {
    println("Hello World!")
}

I have the following in a Dockerfile that I'm using the build the app:

# first download all deps, allows for faster builds when only our code changed
FROM gradle:6.6-jdk14 as cacheRUN mkdir -p /home/gradle/cache_home
ENV GRADLE_USER_HOME /home/gradle/cache_home
COPY build.gradle.kts /home/gradle/kotlin-code/
WORKDIR /home/gradle/kotlin-code
RUN gradle clean build -i --stacktrace
# copy in the deps from the above image, and now pull in the code and build that, creating an executable fat jar
FROM gradle:6.6-jdk14 as builder
COPY --from=cache /home/gradle/cache_home /home/gradle/.gradle
COPY . /usr/src/kotlin-code/
WORKDIR /usr/src/kotlin-code
RUN gradle build -i --stacktrace
RUN ls /usr/src/kotlin-code /usr/src/kotlin-code/build/libs
# Slimmed down running env where we only copy in the jar. This is what actually would be run in prod.
FROM openjdk:14-jdk-alpine
COPY --from=builder /usr/src/kotlin-code/build/libs/gcppubsubtest.jar /bin/runner/run.jar
WORKDIR /bin/runner
CMD ["java","-jar","run.jar"]

When running and building the app as a jar file, I'm getting the following error:
Error: Could not find or load main class MainKt Caused by: java.lang.ClassNotFoundException: MainKt

Can someone tell me whether the syntax I am using is incorrect?

Action Required: Fix Renovate Configuration

There is an error with this repository's Renovate configuration that needs to be fixed. As a precaution, Renovate will stop PRs until it is resolved.

Error type: undefined. Note: this is a nested preset so please contact the preset author if you are unable to fix it yourself.

How to Run Cron Jobs in Kotlin Ktor

Is there a way to run Cron Jobs with Ktor? My end objective is to host a Cron Job written with Kotlin for the Coinverse app's backend service to populate data.

I'm currently hosting multiple Java .jar apps written in Kotlin on AppEngine. I'm looking to refactor these apps into Ktor apps on AppEngine with a Cron Job for scheduled tasks, as the .jar apps have more issues with dependencies.

I'm looking for Ktor's equivalent to Cloud Functions' built-in implementation for Cron Jobs with JavaScript.

functions.pubsub.schedule

Back-up option: Is this alpha/beta available? If Ktor does not have this feature and I want to keep the code in Kotlin, Google has an alpha, Using Kotlin with Google Cloud Functions. It appears Kotlin + Cloud Functions' built-in implementation could be used with this approach.

I've created a corresponding StackOverflow post.

[Policy Bot] found one or more issues with this repository.

Policy Bot found one or more issues with this repository.

  • Default branch is 'main'
  • Branch protection is enabled
  • Renovate bot is enabled
  • Merge commits disabled
  • There is a CODEOWNERS file
  • There is a valid LICENSE.md
  • There is a CODE_OF_CONDUCT.md
  • There is a CONTRIBUTING.md
  • There is a SECURITY.md

Cleaner object creation

In the sample code you initialize a HelloRequest object with:

val request = HelloRequest.newBuilder().setName(name).build()

It would be a big help if you could generate a Kotlin builder for each user protobuf object:

fun helloRequest(block: HelloRequest.Builder.() -> Unit): HelloRequest =
    HelloRequest.newBuilder().let {
        block.invoke(it)
        it.build()
    }

which would allow for much cleaner object creation:

 val request = helloRequest { this.name = name }

One of your fellow Googlers uses this approach and it makes for less cluttered user code.

grpc-hello-world-mvn include Kotlin and Java , Compilation failure

https://github.com/GoogleCloudPlatform/kotlin-samples/blob/master/run/grpc-hello-world-mvn/pom.xml

add:

  <plugin>
    <groupId>org.jetbrains.kotlin</groupId>
    <artifactId>kotlin-maven-plugin</artifactId>
    <version>${kotlin.version}</version>
    <executions>
      <execution>
        <id>compile</id>
        <phase>process-sources</phase>
        <goals>
          <goal>compile</goal>
        </goals>
         <configuration>
            <sourceDirs>
              <sourceDir>${project.basedir}/src/main/kotlin</sourceDir>
              <sourceDir>${project.basedir}/src/main/java</sourceDir>
            </sourceDirs>
          </configuration>
      </execution>
    </executions>
    <configuration>
      <args>
        <arg>-Xopt-in=kotlin.RequiresOptIn</arg>
      </args>
    </configuration>
  </plugin>

error:

[ERROR] Failed to execute goal org.jetbrains.kotlin:kotlin-maven-plugin:1.5.10:compile (compile) on project grpc-hello-world-kotlin: Compilation failure: Compilation failure:
[ERROR] D:\kotlin-samples\run\grpc-hello-world-mvn\src\main\kotlin\io\grpc\examples\helloworld\HelloWorldClient.kt:[22,36] Unresolved reference: GreeterGrpcKt
[ERROR] D:\kotlin-samples\run\grpc-hello-world-mvn\src\main\kotlin\io\grpc\examples\helloworld\HelloWorldClient.kt:[31,23] Unresolved reference: GreeterCoroutineStub
[ERROR] D:\kotlin-samples\run\grpc-hello-world-mvn\src\main\kotlin\io\grpc\examples\helloworld\HelloWorldClient.kt:[31,46] Unresolved reference: GreeterCoroutineStub
[ERROR] D:\kotlin-samples\run\grpc-hello-world-mvn\src\main\kotlin\io\grpc\examples\helloworld\HelloWorldClient.kt:[34,23] Unresolved reference: helloRequest
[ERROR] D:\kotlin-samples\run\grpc-hello-world-mvn\src\main\kotlin\io\grpc\examples\helloworld\HelloWorldClient.kt:[34,38] Unresolved reference: name
[ERROR] D:\kotlin-samples\run\grpc-hello-world-mvn\src\main\kotlin\io\grpc\examples\helloworld\HelloWorldServer.kt:[25,10] None of the following functions can be called with the arguments supplied:
[ERROR] public abstract fun addService(p0: BindableService!): ServerBuilder<>! defined in io.grpc.ServerBuilder
[ERROR] public abstract fun addService(p0: ServerServiceDefinition!): ServerBuilder<
>! defined in io.grpc.ServerBuilder
[ERROR] D:\kotlin-samples\run\grpc-hello-world-mvn\src\main\kotlin\io\grpc\examples\helloworld\HelloWorldServer.kt:[48,39] Unresolved reference: GreeterGrpcKt
[ERROR] D:\kotlin-samples\run\grpc-hello-world-mvn\src\main\kotlin\io\grpc\examples\helloworld\HelloWorldServer.kt:[49,9] 'sayHello' overrides nothing
[ERROR] D:\kotlin-samples\run\grpc-hello-world-mvn\src\main\kotlin\io\grpc\examples\helloworld\HelloWorldServer.kt:[49,48] Unresolved reference: HelloRequest
[ERROR] D:\kotlin-samples\run\grpc-hello-world-mvn\src\main\kotlin\io\grpc\examples\helloworld\HelloWorldServer.kt:[49,64] Unresolved reference: helloReply
[ERROR] D:\kotlin-samples\run\grpc-hello-world-mvn\src\main\kotlin\io\grpc\examples\helloworld\HelloWorldServer.kt:[50,13] Unresolved reference: message
[ERROR] -> [Help 1]
org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.jetbrains.kotlin:kotlin-maven-plugin:1.5.10:compile (compile) on project grpc-hello-world-kotlin: Compilation failure
at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:215)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:156)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:148)
at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:117)
at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:81)
at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build (SingleThreadedBuilder.java:56)
at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:128)
at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:305)
at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:192)
at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:105)
at org.apache.maven.cli.MavenCli.execute (MavenCli.java:957)
at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:289)
at org.apache.maven.cli.MavenCli.main (MavenCli.java:193)
at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62)
at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke (Method.java:566)
at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced (Launcher.java:282)
at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:225)
at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:406)
at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:347)
at org.codehaus.classworlds.Launcher.main (Launcher.java:47)
Caused by: org.jetbrains.kotlin.maven.KotlinCompilationFailureException: Compilation failure
at org.jetbrains.kotlin.maven.MavenPluginLogMessageCollector.throwKotlinCompilerException (MavenPluginLogMessageCollector.java:111)
at org.jetbrains.kotlin.maven.KotlinCompileMojoBase.execute (KotlinCompileMojoBase.java:212)
at org.jetbrains.kotlin.maven.K2JVMCompileMojo.execute (K2JVMCompileMojo.java:222)
at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo (DefaultBuildPluginManager.java:137)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:210)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:156)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:148)
at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:117)
at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:81)
at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build (SingleThreadedBuilder.java:56)
at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:128)
at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:305)
at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:192)
at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:105)
at org.apache.maven.cli.MavenCli.execute (MavenCli.java:957)
at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:289)
at org.apache.maven.cli.MavenCli.main (MavenCli.java:193)
at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62)
at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke (Method.java:566)
at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced (Launcher.java:282)
at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:225)
at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:406)
at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:347)
at org.codehaus.classworlds.Launcher.main (Launcher.java:47)

Migrating Kotlin Jar/AppEngine Project: Exception in thread “Timer-0”

Overview

There is an issue when attempting to migrate a Kotlin AppEngine project from an old MacBook Pro (MBP) to a new MBP, when running the Main method and building a .jar file locally.

The Main method in IntelliJ fails intermittently on the new MBP. The old .jar runs as expected on the new MBP, and the new .jar runs as expected on the old MBP.

Expected

  1. Run existing local .jar file from Kotlin project on the old MBP.
  2. Clone Kotlin project from GitHub repository into local IntelliJ project on new MBP.
  3. Build .jar on new MBP.
  4. Run .jar on new MBP.
  5. Host .jar on Google AppEngine instance.

Observed

  1. Running .jar on existing MBP works as expected.
  2. Running main method with the same code runs intermittently on the new MBP after the GitHub repo is cloned locally.

Error

The Main method runs on the old MBP as expected, but not on the new MBP with the following error.

Exception in thread "Timer-0" com.google.cloud.storage.StorageException: 401 Unauthorized
at com.google.cloud.storage.spi.v1.HttpStorageRpc.translate(HttpStorageRpc.java:229)
at com.google.cloud.storage.spi.v1.HttpStorageRpc.create(HttpStorageRpc.java:310)
at com.google.cloud.storage.StorageImpl$3.call(StorageImpl.java:196)
at com.google.cloud.storage.StorageImpl$3.call(StorageImpl.java:193)
at com.google.api.gax.retrying.DirectRetryingExecutor.submit(DirectRetryingExecutor.java:105)
at com.google.cloud.RetryHelper.run(RetryHelper.java:76)
at com.google.cloud.RetryHelper.runWithRetries(RetryHelper.java:50)
at com.google.cloud.storage.StorageImpl.internalCreate(StorageImpl.java:192)
at com.google.cloud.storage.StorageImpl.create(StorageImpl.java:154)
at content.SaveContentKt.saveContent(SaveContent.kt:38)
at content.ContentTasks.generateContent(ContentTasks.kt:55)
at content.ContentTasks.run(ContentTasks.kt:41)
at java.base/java.util.TimerThread.mainLoop(Timer.java:556)
at java.base/java.util.TimerThread.run(Timer.java:506)
Caused by: com.google.api.client.googleapis.json.GoogleJsonResponseException: 401 Unauthorized
at com.google.api.client.googleapis.json.GoogleJsonResponseException.from(GoogleJsonResponseException.java:150)
at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:113)
at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:40)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:554)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:474)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:591)
at com.google.cloud.storage.spi.v1.HttpStorageRpc.create(HttpStorageRpc.java:307)
... 12 more

Configuration

The gradle-wrapper.properties Gradle, IntelliJ Preferences Gradle JVM, Project SDK, Run/Debug Configurations JRE, and Project language level versions are the same across both machines.

Preferences > Gradle

  • Use Gradle from: 'gradle-wrapper.properties' file(Gradle 6.0.1)

  • Gradle JVM: Library/Java/JavaVirtualMachines/12.0.1

File > Project Structure... > Project

  • Project SDK: 12.0.1
  • Project language level: 11

Running .jar file: Project Structure > Project Settings > Artifacts > Add > JAR > From modules with dependencies...

  • Module: coinverse-media.main
  • Main Class: Initialization

Lastly, build artifact and run .jar file.

build.gradle

buildscript {
    ext.kotlin_version = '1.3.61'

    repositories {
        mavenCentral()
    }
    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}

plugins {
    id 'java'
    id 'org.jetbrains.kotlin.jvm' version '1.2.51'
}

version '1.0-SNAPSHOT'

sourceCompatibility = 1.8

repositories {
    mavenCentral()
}

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8"
    implementation 'com.squareup.retrofit2:retrofit:2.7.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.7.0'
    implementation 'com.squareup.retrofit2:adapter-rxjava:2.7.0'
    implementation 'com.google.firebase:firebase-admin:6.12.0'
    implementation 'com.google.cloud:google-cloud-storage:1.102.0'
    implementation 'com.google.apis:google-api-services-youtube:v3-rev20190827-1.30.1'
}

compileKotlin {
    kotlinOptions.jvmTarget = "1.8"
}
compileTestKotlin {
    kotlinOptions.jvmTarget = "1.8"
}

Attempted Solutions

  1. Invalidate Caches / Restart...: This appears to fix the issue for a few times running the Main method, then the error continues to show.
  2. ./gradlew clean build
  3. Gradle > Reimport All Gradle Projects
  4. Updating to the latest Gradle version.
  5. Ensure existing MBP and new MBP are running on the same IntelliJ/Project/Run configurations.
  6. Potentially related build dependency conflict issue: Guava Dependency Breaking Jar Built With Kotlin.

Build Data

6:09:42 PM: Executing task 'assemble'...

Task :compileKotlin UP-TO-DATE

Task :compileJava NO-SOURCE

Task :processResources NO-SOURCE

Task :classes UP-TO-DATE

Task :inspectClassesForKotlinIC UP-TO-DATE

Task :jar UP-TO-DATE

Task :assemble UP-TO-DATE

BUILD SUCCESSFUL in 75ms
3 actionable tasks: 3 up-to-date
6:09:42 PM: Task execution finished 'assemble'.

  • Hidden files
    enter image description here

Here is the StackOverflow post. I'll update each platform once the solution is found.

[emojify-codelab]: gcloud CLI init is not explained

Problem

In step 6 of the tutorial it asks to create an App Engine application using:

$ gcloud app create

but at that point, the user won't be logged in with gcloud if this is their first time using the sdk and the command will fail.

Possible solution

There are two easy steps that need to happen before the App Engine application could be created:

1. Authentication
This will prompt the user to authenticate using their Google accounts with an easy to follow explanation

$ gcloud auth login

2. Set project
This will let the user select the project created in step 2 to be used by the gcloud sdk

$ gcloud config set project <PROJECT_ID>

grpc-hello-world-mvn does not build in ubuntu

After downloading repo at 41339a3, grpc-hello-world-mvn it does not build properly.
There is an error report by ktlin-maven-plugin: object GreeterGrpcKt should be declared in a file named GreeterGrpcKt.kt

Looking at generated source files, effectively there is no GreeterGrpcKt.kt file, instead there is one with same expected information but named HelloWorldGrpcKt.kt (see image at the bottom). Due to this, HelloWorldServer and HelloWorldClient are not able to find required dependencies as well.

Here is the information about my OS

[INFO] Detecting the operating system and CPU architecture
[INFO] ------------------------------------------------------------------------
[INFO] os.detected.name: linux
[INFO] os.detected.arch: x86_64
[INFO] os.detected.version: 5.4
[INFO] os.detected.version.major: 5
[INFO] os.detected.version.minor: 4
[INFO] os.detected.release: ubuntu
[INFO] os.detected.release.version: 20.04
[INFO] os.detected.release.like.ubuntu: true
[INFO] os.detected.release.like.debian: true
[INFO] os.detected.classifier: linux-x86_64

Here are the dependencies being downloaded related to protoc-gen-grpc-kotlin

[INFO] --- protobuf-maven-plugin:0.5.0:compile-custom (grpc-kotlin) @ grpc-hello-world-kotlin ---
Downloading from central: https://repo.maven.apache.org/maven2/io/grpc/protoc-gen-grpc-kotlin/0.1.3/protoc-gen-grpc-kotlin-0.1.1.pom
Downloaded from central: https://repo.maven.apache.org/maven2/io/grpc/protoc-gen-grpc-kotlin/0.1.3/protoc-gen-grpc-kotlin-0.1.1.pom (3.1 kB at 15 kB/s)
Downloading from central: https://repo.maven.apache.org/maven2/io/grpc/protoc-gen-grpc-kotlin/0.1.3/protoc-gen-grpc-kotlin-0.1.1-linux-x86_64.exe
Downloaded from central: https://repo.maven.apache.org/maven2/io/grpc/protoc-gen-grpc-kotlin/0.1.3/protoc-gen-grpc-kotlin-0.1.1-linux-x86_64.exe (21 MB at 1.0 MB/s)

Generated files tree
Captura de pantalla de 2020-08-16 20-14-56

Security Policy violation Binary Artifacts

This issue was automatically created by Allstar.

Security Policy Violation
Project is out of compliance with Binary Artifacts policy: binaries present in source code

Rule Description
Binary Artifacts are an increased security risk in your repository. Binary artifacts cannot be reviewed, allowing the introduction of possibly obsolete or maliciously subverted executables. For more information see the Security Scorecards Documentation for Binary Artifacts.

Remediation Steps
To remediate, remove the generated executable artifacts from the repository.

Artifacts Found

  • appengine/springboot/.mvn/wrapper/maven-wrapper.jar
  • getting-started/android-with-appengine/backend/.mvn/wrapper/maven-wrapper.jar
  • run/grpc-hello-world-mvn/.mvn/wrapper/maven-wrapper.jar
  • run/plain-hello-world/.mvn/wrapper/maven-wrapper.jar
  • run/quarkus-hello-world/.mvn/wrapper/maven-wrapper.jar

Additional Information
This policy is drawn from Security Scorecards, which is a tool that scores a project's adherence to security best practices. You may wish to run a Scorecards scan directly on this repository for more details.


⚠️ There is an updated version of this policy result! Click here to see the latest update


Allstar has been installed on all Google managed GitHub orgs. Policies are gradually being rolled out and enforced by the GOSST and OSPO teams. Learn more at http://go/allstar

This issue will auto resolve when the policy is in compliance.

Issue created by Allstar. See https://github.com/ossf/allstar/ for more information. For questions specific to the repository, please contact the owner or maintainer.

Firebase Auth Not Working With Kotlin Ktor App On AppEngine

Issue

When deploying a Ktor Kotlin application to AppEngine per the Ktor tutorial, the Firestore server authentication is not working, thus data is not being written to the specified Firestore database.

Data is written as expected to Firestore both when the app is run directly in the IntelliJ IDE as well as when it is run with ktor's implementation via the gradle appengineRun command.

Note: the same Firebase auth implementation using a service account works when deployed in a .Jar to AppEngine.

There are two sets of AppEngine/Firebase projects for both a staging and production environment. Prior to deploying with the gradle appengineDeploy command the correct SDK configuration been activated and verified via the command gcloud config configurations list.

enter image description here

The strange part is that a few of the apps deployed with these strategies did write to Firestore, however upon deploying the app again Firestore did not show new data being written to it.

Implementation

Ktor Setup

I have the standard ktor required files. I also have an old MANIFEST.MF file from an older implementation. Could that be causing issues?

src/main/resources/application.conf

ktor {
  application {
  modules = [ Initialization.main ]
  }
}

src/main/resources/webapp/WEB-INF/

appengine-web.xml

<?xml version="1.0" encoding="utf-8"?>
<appengine-web-app xmlns="http://appengine.google.com/ns/1.0">
    <threadsafe>true</threadsafe>
    <runtime>java8</runtime>
</appengine-web-app>

web.xml

<?xml version="1.0" encoding="ISO-8859-1" ?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
<servlet>
    <display-name>KtorServlet</display-name>
    <servlet-name>KtorServlet</servlet-name>
    <servlet-class>io.ktor.server.servlet.ServletApplicationEngine</servlet-class>
    <!-- path to application.conf file, required -->
    <init-param>
        <param-name>io.ktor.config</param-name>
        <param-value>application.conf</param-value>
    </init-param>
</servlet>
<servlet-mapping>
    <servlet-name>KtorServlet</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

logging.properties

.level = INFO

src/main/META-INF/MANIFEST>MF

Manifest-Version: 1.0
Main-Class: Initialization

Dependencies

For authentication strategies outlined below #1-3 the Firebase Admin library is used: compile 'com.google.firebase:firebase-admin:6.5.0'

For authentication strategy #4 the Google Cloud Firestore library is used: compile 'com.google.cloud:google-cloud-firestore:0.58.0-beta'

build.gradle

group 'coinverse'
version '1.0-SNAPSHOT'

buildscript {
    ext.kotlin_version = '1.2.61'
    ext.junitJupiterVersion  = '5.0.3'
    ext.ktor_version = '0.9.4'
    ext.appengine_version = '1.9.60'
    ext.appengine_plugin_version = '1.3.4'

repositories {
    mavenCentral()
    jcenter()
}
dependencies {
    classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    classpath 'org.junit.platform:junit-platform-gradle-plugin:1.0.3'
    classpath "com.google.cloud.tools:appengine-gradle-plugin:$appengine_plugin_version"
    }
}

apply plugin: 'java'
apply plugin: 'kotlin'
apply plugin: 'war'
apply plugin: 'com.google.cloud.tools.appengine'

sourceSets {
    main.kotlin.srcDirs = [ 'src/main/kotlin' ]
}

sourceCompatibility = 1.8

repositories {
mavenCentral()
jcenter()
maven { url "https://kotlin.bintray.com/ktor" }
}

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
    testCompile group: 'junit', name: 'junit', version: '4.12'
    testCompile("org.junit.jupiter:junit-jupiter-api:${junitJupiterVersion}")
        testRuntime("org.junit.jupiter:junit-jupiter-engine:${junitJupiterVersion}")
        testCompile("org.assertj:assertj-core:3.10.0")
        testCompileOnly('org.apiguardian:apiguardian-api:1.0.0')
        compile 'com.squareup.retrofit2:retrofit:2.3.0'
        compile 'com.squareup.retrofit2:converter-gson:2.3.0'
        compile 'com.squareup.retrofit2:adapter-rxjava:2.3.0'
        compile 'io.reactivex.rxjava2:rxjava:2.2.0'
        compile 'com.google.cloud:google-cloud-firestore:0.58.0-beta'
        // Or compile 'com.google.cloud:google-cloud-firestore:0.58.0-beta'
        compile 'com.google.firebase:firebase-admin:6.5.0'
        compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
        compile "io.ktor:ktor-server-servlet:$ktor_version"
        compile "io.ktor:ktor-html-builder:$ktor_version"
        providedCompile "com.google.appengine:appengine:$appengine_version"
}

kotlin.experimental.coroutines = 'enable'

compileKotlin {
    kotlinOptions.jvmTarget = "1.8"
}
compileTestKotlin {
    kotlinOptions.jvmTarget = "1.8"
}

task run(dependsOn: appengineRun)

appengine {
    deploy {
        version = 'price-staging-1021653pm'
        stopPreviousVersion = false
    }
}

Initializing Firebase Strategies

1. Initialize on Google Cloud Platform

This method is promising as credentials are managed automatically.

// Use the application default credentials
GoogleCredentials credentials = GoogleCredentials.getApplicationDefault();
FirebaseOptions options = new FirebaseOptions.Builder()
    .setCredentials(credentials)
    .setProjectId(projectId)
    .build();
FirebaseApp.initializeApp(options);

Firestore db = FirestoreClient.getFirestore();

2. Initialize on your own server

I've confirmed in GCPs IAM & admin > Service accounts that the key id's match with the Json object being used to authenticate.

I'm using this strategy successfully in another Firestore connected app deployed to AppEngine. The working app is built as a .Jar and deployed directly to AppEngine without using ktor, but rather with the steps outlined here.

// Use a service account
InputStream serviceAccount = new FileInputStream("path/to/serviceAccount.json");
GoogleCredentials credentials = GoogleCredentials.fromStream(serviceAccount);
FirebaseOptions options = new FirebaseOptions.Builder()
    .setCredentials(credentials)
    .build();
FirebaseApp.initializeApp(options);

Firestore db = FirestoreClient.getFirestore();

In my working .Jar built app I'm passing in the Json object programmatically to avoid issues with the file not being found. I tried the same programmatic implementation for this ktor application. It worked with gradle appengineRun but not when deployed.

val credentials = GoogleCredentials.fromStream(Gson().toJson(FirebaseCredentials(
            "service_account",
            "project-name",
            "asdfghjkl",
            "keyStringHere",
            "[email protected]",
            "1234567890",
            "https://accounts.google.com/o/oauth2/auth",
            "https://oauth2.googleapis.com/token",
            "https://www.googleapis.com/oauth2/v1/certs",
           "https://www.googleapis.com/robot/v1/metadata/x509/firebase-adminsdk-dhr30%40project-name-staging.iam.gserviceaccount.com"
    )).byteInputStream())
    val options = FirebaseOptions.Builder()
            .setCredentials(credentials)
            .setDatabaseUrl("https://project-name-staging.firebaseio.com")
            .build()

    FirebaseApp.initializeApp(options)

3. Initialize on your own server (Firebase console setup)

The only difference between #2 is this setup adds .setDatabaseUrl("https://yourProjectName.firebaseio.com").

enter image description here

4. Initialize cloud Firestore

FirestoreOptions firestoreOptions =
FirestoreOptions.getDefaultInstance().toBuilder()
    .setProjectId(projectId)
    .build();
Firestore db = firestoreOptions.getService();

Accessing Firestore Object

For #1-3 the Firebase app is initialized right away in the application's main() method. Then, the Firestore object is accessed from an object.

FirebaseClient.Kt

object FirebaseClient {
    val firestore: Firestore
    init {
        firestore = FirestoreClient.getFirestore()
    }
}

For #4 the Firestore object is created in the Kotlin object's init{...} and stored in the object as a value.

FirebaseClient.Kt

object FirebaseClient {
    val firestore: Firestore

    init {
        val firestoreOptions = FirestoreOptions.getDefaultInstance().toBuilder()
            .setTimestampsInSnapshotsEnabled(true)
            .setProjectId("project-name")
            .build()
        firestore = firestoreOptions.service
    }
}

Writing to Firestore

FirebaseClient.firestore.collection(someCollection).document(someDocument).collection(anotherCollection).add(someObject)

I've created a corresponding StackOverflow post.

Add Authentication to Root README

It's not a great experience having the 7-step authentication process outlined in each README. Instead, let's outline it in ONE PLACE (in the root README.md) and link to it from the sample READMEs.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.