com.jcraft.jsch.JSchException: Auth fail in ktor kotlin - kotlin

I am new to programming.
I have a built a backend using ktor and now I want to deploy that app to a server.
I have tried deploying it multiple times on a virtual private server but every time I get error com.jcraft.jsch.JSchException: Auth fail.
I am using ssh keys to authenticate.
My Build.gradle.kts file
val ktor_version: String by project
val kotlin_version: String by project
val logback_version: String by project
val kmongo_version:String by project
val commons_codec_version:String by project
plugins {
kotlin("jvm") version "1.7.21"
id("io.ktor.plugin") version "2.1.3"
id("org.jetbrains.kotlin.plugin.serialization") version "1.7.21"
id("com.github.johnrengelman.shadow") version "5.2.0"
}
group = "com.androidjunior9"
version = "0.0.1"
application {
mainClass.set("io.ktor.server.netty.EngineMain")
project.setProperty("mainClassName", mainClass.get())
val isDevelopment: Boolean = project.ext.has("development")
applicationDefaultJvmArgs = listOf("-Dio.ktor.development=$isDevelopment")
}
repositories {
mavenCentral()
maven { url=
uri("https://maven.pkg.jetbrains.space/public/p/ktor/eap")
}
}
val sshAntTask = configurations.create("sshAntTask")
dependencies {
implementation("io.ktor:ktor-server-core-jvm:$ktor_version")
implementation("io.ktor:ktor-server-websockets-jvm:$ktor_version")
implementation("io.ktor:ktor-server-content-negotiation-jvm:$ktor_version")
implementation("io.ktor:ktor-serialization-kotlinx-json-jvm:$ktor_version")
implementation("io.ktor:ktor-server-call-logging-jvm:$ktor_version")
implementation("io.ktor:ktor-server-netty-jvm:$ktor_version")
implementation("ch.qos.logback:logback-classic:$logback_version")
implementation("io.ktor:ktor-server-sessions:$ktor_version")
testImplementation("io.ktor:ktor-server-tests-jvm:$ktor_version")
testImplementation("org.jetbrains.kotlin:kotlin-test-junit:$kotlin_version")
implementation("io.ktor:ktor-server-auth-jvm:$ktor_version")
implementation("io.ktor:ktor-server-auth-jwt-jvm:$ktor_version")
// Kmongo
implementation("org.litote.kmongo:kmongo:$kmongo_version")
implementation("org.litote.kmongo:kmongo-coroutine:$kmongo_version")
implementation("commons-codec:commons-codec:$commons_codec_version")
sshAntTask("org.apache.ant:ant-jsch:1.10.12")
}
tasks.withType<com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar> {
manifest {
attributes(
"Main-Class" to application.mainClass.get()
)
}
}
ant.withGroovyBuilder {
"taskdef"(
"name" to "scp",
"classname" to "org.apache.tools.ant.taskdefs.optional.ssh.Scp",
"classpath" to configurations.get("sshAntTask").asPath
)
"taskdef"(
"name" to "ssh",
"classname" to "org.apache.tools.ant.taskdefs.optional.ssh.SSHExec",
"classpath" to configurations.get("sshAntTask").asPath
)
}
task("deploy") {
dependsOn("clean", "shadowJar")
ant.withGroovyBuilder {
doLast {
val knownHosts = File.createTempFile("knownhosts", "txt")
val user = "root"
val host = "Ip"
val key = file("keys/newkey")
val jarFileName = "jarfile"
try {
"scp"(
"file" to file("build/libs/$jarFileName"),
"todir" to "$user#$host:/root/service",
"keyfile" to "$key",
"trust" to true,
"knownhosts" to knownHosts
)
"ssh"(
"host" to host,
"username" to user,
"keyfile" to "$key",
"trust" to true,
"knownhosts" to knownHosts,
"command" to "mv /root/service/$jarFileName /root/service/service.jar"
)
"ssh"(
"host" to host,
"username" to user,
"keyfile" to "$key",
"trust" to true,
"knownhosts" to knownHosts,
"command" to "systemctl stop service"
)
"ssh"(
"host" to host,
"username" to user,
"keyfile" to "$key",
"trust" to true,
"knownhosts" to knownHosts,
"command" to "systemctl start service"
)
} finally {
knownHosts.delete()
}
}
}
}
What Solutions I tried:
Used New ssh key pair.
Changed sshd_config configurations.
Changed File Permissions.
Checked that I am providing the right ssh key.
Changed dependency versions.
Edit
Solution:
Check your ubuntu version because jsch is not working well with ubuntu's latest version's. Try using earlier version like 20.04 or 18.04.

Related

Ktor java.lang.NoClassDefFoundError: io/ktor/server/cio/CIO

I developed a simple project using ktor
here is my Application.kt
fun main() {
embeddedServer(
factory = CIO, port = 8080, host = "0.0.0.0"
) {
configDependencyInjection()
configSerialization()
configJwtAuthentication()
configStatusPages()
configRequestValidation()
configUserRouting()
Database.connect(
url = "jdbc:postgresql://localhost:5432/coffeehouse",
driver = "org.postgresql.Driver",
user = "postgres",
password = "74279744fz"
)
transaction {
SchemaUtils.drop(Users, CoffeeHouses)
SchemaUtils.create(Users, CoffeeHouses)
}
}.start(wait = true)
}
and here is my build.gradle.kts
val ktorVersion: String by project
val kotlinVersion: String by project
val logbackVersion: String by project
val exposedVersion: String by project
val koinVersion: String by project
val postgresVersion: String by project
plugins {
application
kotlin("jvm") version "1.7.20"
id("io.ktor.plugin") version "2.1.2"
id("org.jetbrains.kotlin.plugin.serialization") version "1.7.20"
}
group = "ir.coffee"
version = "0.0.1"
application {
mainClass.set("ir.coffee.ApplicationKt")
val isDevelopment: Boolean = project.ext.has("development")
applicationDefaultJvmArgs = listOf("-Dio.ktor.development=$isDevelopment")
}
repositories {
mavenCentral()
}
tasks.withType<Jar> {
manifest {
attributes["Main-class"] = application.mainClass
}
}
dependencies {
implementation("io.ktor:ktor-server-content-negotiation-jvm:$ktorVersion")
implementation("io.ktor:ktor-server-core-jvm:$ktorVersion")
implementation("io.ktor:ktor-serialization-kotlinx-json-jvm:$ktorVersion")
implementation("io.ktor:ktor-server-cio-jvm:$ktorVersion")
implementation("io.ktor:ktor-server-auth:$ktorVersion")
implementation("io.ktor:ktor-server-auth-jwt:$ktorVersion")
implementation("io.ktor:ktor-server-request-validation:$ktorVersion")
implementation("io.ktor:ktor-server-status-pages:$ktorVersion")
implementation("ch.qos.logback:logback-classic:$logbackVersion")
implementation("org.jetbrains.exposed:exposed-core:$exposedVersion")
implementation("org.jetbrains.exposed:exposed-dao:$exposedVersion")
implementation("org.jetbrains.exposed:exposed-jdbc:$exposedVersion")
implementation("org.postgresql:postgresql:$postgresVersion")
implementation("io.insert-koin:koin-ktor:$koinVersion")
implementation("io.insert-koin:koin-logger-slf4j:$koinVersion")
testImplementation("io.ktor:ktor-server-tests-jvm:$ktorVersion")
testImplementation("org.jetbrains.kotlin:kotlin-test-junit:$kotlinVersion")
}
when I run the project, it works fine and i can make a jar file with
./gradlew installDist command.
but when I try to run the jar file with java -jar ir.coffee-0.0.1.jar command
i get this error:
Exception in thread "main" java.lang.NoClassDefFoundError: io/ktor/server/cio/CIO
at ir.coffee.ApplicationKt.main(Application.kt:16)
at ir.coffee.ApplicationKt.main(Application.kt)
Caused by: java.lang.ClassNotFoundException: io.ktor.server.cio.CIO at
java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:581)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:522)
... 2 more
any suggestion how can I fix this?
The installDist task packs the project's class files in a JAR without dependencies. So to solve your problem you can either specify paths to the dependencies via the -classpath flag while executing java or pack all dependencies in a JAR (Gradle Shadow plugin).

Publishing SNAPSHOT versions of Android libraries using Android Gradle Plugin 7+

I have an Android library (gradle multi module project) where I publish to two different Nexus Maven2 repositories with strict versioning, a release repository and a snapshot repository.
This has worked well using Android Gradle Plugin 4.0.1.
command:
gradlew -PmavenRepoUrl=https://myserver.com/nexus/repository/project-snapshots -PmavenRepoCredentialType=PasswordType -PmavenUser=$NEXUS_USER -PmavenPassword=$NEXUS_PASSWORD publishDebugPublicationToMavenRepository
build.gradle.kts:
plugins {
id("com.android.library")
id("maven-publish")
...
}
val mavenRepoUrl: String by project
val mavenRepoCredentialType: String by project
val mavenPublicAccessKey: String by project
val mavenPublicSecretKey: String by project
val mavenUser: String by project
val mavenPassword: String by project
afterEvaluate {
publishing {
repositories {
maven(url = mavenRepoUrl) {
when (mavenRepoCredentialType) {
"AwsCredentialType" -> {
credentials(AwsCredentials::class) {
accessKey = mavenPublicAccessKey
secretKey = mavenPublicSecretKey
}
}
"PasswordType" -> {
credentials(PasswordCredentials::class) {
username = mavenUser
password = mavenPassword
}
}
else -> {
logger.log(ERROR, "Unsupported credential type: $mavenRepoCredentialType")
}
}
}
}
publications {
create<MavenPublication>("Release") {
from(components.getByName("release"))
groupId = project.group as String
artifactId = "my-android-project-${project.name}"
version = project.version as String
}
create<MavenPublication>("Debug") {
from(components.getByName("debug"))
groupId = project.group as String
artifactId = "my-android-project-${project.name}"
version = project.version as String
}
}
}
}
But after updating to Android Gradle Plugin 7.0+ I'm getting this error:
Execution failed for task ':core:publishDebugPublicationToMavenRepository'.
> Failed to publish publication 'Debug' to repository 'maven'
> Could not PUT 'https://myserver.com/nexus/repository/project-snapshots/com/myproject/1.1.0-M25/my-project-1.1.0-M25.aar'. Received status code 400 from server: Repository version policy: SNAPSHOT does not allow version: 1.1.0-M25
(When upgrading Android Gradle Plugin I had to remove the "isDebuggable" attribute from the build variants. Maybe that's a clue?).
To troubleshoot I tried explicitly setting the version to "-SNAPSHOT" for debug builds, build.gradle.kts:
publications {
create<MavenPublication>("Debug") {
...
version = (project.version as String) + "-SNAPSHOT"
...
}
}
but then I get this error:
* What went wrong:
Could not determine the dependencies of task ':my-module-2:publishDebugPublicationToMavenRepository'.
> Publishing is not able to resolve a dependency on a project with multiple publications that have different coordinates.
Found the following publications in project ':my-modulue':
- Maven publication 'Release' with coordinates com.myproject:my-module:1.1.0-M25
- Maven publication 'Debug' with coordinates com.myproject:my-module:1.1.0-M25-SNAPSHOT
(related: https://github.com/gradle/gradle/issues/12324)
My setup:
Multi module project with Android library modules
Android Gradle Plugin 7.0.1
Gradle 7.0.2, 7.1.1, 7.2 (doesn't work with any of them)
Kotlin Gradle DSL
Is this a regression caused by the Android Gradle Plugin or is there a way to solve my problem?

Ktlint ignores .editorconfig

I wanted to try out Kotlin and ktlint and I was happy to see that it supports tab indentation via the editorconfig file (since this PR). Sadly it doesn't seem to work for me. I haven't used editorconfig before, I might have made some simple mistake.
My .editorconfig in the root folder:
indent_style = tab
My gradle file:
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
val koinVersion: String by project
val junitVersion: String by project
plugins {
application
kotlin("jvm") version "1.4.30"
id("org.jlleitschuh.gradle.ktlint") version "10.0.0"
}
group = "me.me"
version = "1.0-SNAPSHOT"
application {
mainClassName = "de.me.bot.translate.MainKt"
}
repositories {
mavenCentral()
jcenter()
}
dependencies {
implementation("com.sksamuel.hoplite:hoplite-core:+")
implementation("org.koin:koin-core:$koinVersion")
testImplementation("org.koin:koin-test:$koinVersion")
testImplementation(kotlin("test-junit5"))
testImplementation("org.junit.jupiter:junit-jupiter-api:$junitVersion")
testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:$junitVersion")
}
tasks.test {
useJUnitPlatform()
}
tasks.withType<KotlinCompile>() {
kotlinOptions.jvmTarget = "13"
}
However running gradle ktlintCheck still throws exceptions because of unexpected tab characters. I don't understand why. I ran it with --debug, but it didn't give me any useful information.
Here is my project: github.com
EditorConfig specification states:
With the exception of the root key, all pairs MUST be located under a section to take effect.
So your .editorconfig file should be:
root = true
[*.{kt,kts}]
indent_style = tab

How to use Apollo Android from Kotlin, but without Android?

I want to use Apollo Android to query the GitHub GraphQL api, using Kotlin with the Gradle Kotlin DSL but not on Android.
Error message
I do run into a specific problem, but that's probably because there is something wrong in my setup elsewhere.
To summarize, I have a ViewLogin.graphql file, from which a ViewLoginQuery is generated, but when I try to use ViewLoginQuery.builder() then unresolved reference: builder is the problem.
Setup
As mentioned in https://github.com/apollographql/apollo-android/issues/1573, it should be possible to use Apollo Android without Android.
Environment
I'm using Arch Linux and IntelliJ, with the JS GraphQL IntelliJ plugin installed.
Gradle Kotlin DSL build file
When writing the build file I already ran into a problem: I did not manage to avoid using the deprecated buildscript block.
The plugin shown at https://plugins.gradle.org/plugin/com.apollographql.apollo is apparently the incubating plugin as mentioned at https://github.com/apollographql/apollo-android/issues/1573#issuecomment-575613238 which is not yet ready.
The following build file seems to apply the plugin correctly:
buildscript {
repositories {
maven {
url = uri("https://plugins.gradle.org/m2/")
}
jcenter()
}
dependencies {
classpath("com.apollographql.apollo:apollo-gradle-plugin:1.2.2")
}
}
apply(plugin = "com.apollographql.android")
plugins {
val kotlinVersion = "1.3.60"
application
kotlin("jvm") version kotlinVersion
java
idea
}
dependencies {
implementation(kotlin("stdlib"))
// Apollo and dependencies
implementation("com.apollographql.apollo:apollo-runtime:1.2.2")
implementation("com.squareup.okio:okio:2.4.3")
implementation("org.jetbrains:annotations:13.0")
testImplementation("org.jetbrains:annotations:13.0")
}
repositories {
mavenCentral()
mavenLocal()
jcenter()
}
tasks.withType<com.apollographql.apollo.gradle.ApolloCodegenTask> {
generateKotlinModels.set(true)
}
so after syncing, I have the apollo Gradle tasks available.
Downloading the schema
I installed the Apollo cli interface and then, following the Apollo docs, I ran
apollo schema:download --endpoint=https://api.github.com/graphql --header="Authorization: Bearer mytoken"
which gave me a schema.json that I put in src/main/graphql/nl/mypackage/myapplication/schema.json.
Example query
I have a file src/main/graphql/nl/mypackage/myapplication/ViewLogin.graphql which contains query ViewLogin { viewer { login }}.
IntelliJ shows an error on both viewer and login, saying Unknown field "viewer" on object type "Query". Did you mean "viewer"?. But this may be a misconfiguration of the JS GraphQL plugin.
I tried to configure JS GraphQL by adding a file src/main/graphql/nl/mypackage/myapplication/.graphqlconfig containing
{
"name": "GitHub GraphQL Schema",
"schemaPath": "schema.json",
"extensions": {
"endpoints": {
"Default GraphQL Endpoint": {
"url": "https://api.github.com/graphql",
"headers": {
"user-agent": "JS GraphQL"
},
"introspect": true
}
}
}
}
but the errors remain.
Then I executed the Gradle task generateApolloClasses which generated a build/generated/source/apollo/classes/main/nl/mypackage/myapplication/ViewLoginQuery.kt file.
When I open that file, no errors are shown and everything looks ok.
Execute the query
In a file src/main/kotlin/nl/mypackage/myapplication/GraphqlExample.kt I tried to use the query, following the docs at https://www.apollographql.com/docs/android/essentials/get-started/#consuming-code
but when I try to use ViewLoginQuery.builder() then builder is not recognized (by IntelliJ, and also when I try to run it).
I tried searching in superclasses of ViewLoginQuery but I couldn't find anything about a builder.
I don't know where that builder is supposed to be, but you can instantiate the query directly and use that.
This is an example of consumer code (last tested with version 2.1.0):
import com.apollographql.apollo.ApolloCall
import com.apollographql.apollo.ApolloClient
import com.apollographql.apollo.api.Response
import com.apollographql.apollo.exception.ApolloException
import okhttp3.OkHttpClient
fun main(args: Array<String>) {
val serverUrl = "https://api.github.com/graphql"
val authHeader = args[0]
// Add authentication header for GitHub
val okHttpClient = OkHttpClient.Builder()
.addInterceptor { chain ->
val builder = chain.request().newBuilder()
builder.header("Authorization", "Bearer $authHeader")
chain.proceed(builder.build())
}
.build()
val apolloClient = ApolloClient.builder()
.serverUrl(serverUrl)
.okHttpClient(okHttpClient)
.build()
val query = ViewLoginQuery()
apolloClient.query(query).enqueue(object : ApolloCall.Callback<ViewLoginQuery.Data?>() {
override fun onResponse(dataResponse: Response<ViewLoginQuery.Data?>) {
val data = dataResponse.data
if (data == null) {
println("No data received")
println(dataResponse.errors)
} else {
println(dataResponse.data?.viewer?.login)
}
}
override fun onFailure(e: ApolloException) {
println(e.message)
}
})
}
To fix the 'unknown field' errors in the .graphql file, you have to download the schema as a schema.graphql instead of schema.json, see https://github.com/jimkyndemeyer/js-graphql-intellij-plugin/issues/305 for the issue report.
You also have to provide the github token in the header. Change your .graphqlconfig to the following:
{
"name": "GitHub GraphQL Schema",
"schemaPath": "./schema.graphql",
"extensions": {
"endpoints": {
"Default GraphQL Endpoint": {
"url": "https://api.github.com/graphql",
"headers": {
"user-agent": "JS GraphQL",
"Authorization": "Bearer ${env:GITHUB_GRAPHQL_TOKEN}"
},
"introspect": true
}
}
}
}
You can now easily download the new schema by clicking the 'run introspection query' gutter icon next to the "url": line.
You will get a popup asking for the token. Unfortunately the plugin does not yet support reading the environment variable from anywhere, see for example https://github.com/jimkyndemeyer/js-graphql-intellij-plugin/issues/285
However, Apollo Android requires a schema.json, so you need to keep the one you downloaded!
Since Apollo Android will (at least for me) error on the schema.graphql file, tell it to ignore that file by changing the Gradle task configuration to
apollo {
generateKotlinModels.set(true)
graphqlSourceDirectorySet.srcDir("src/main/graphql")
graphqlSourceDirectorySet.include("**/*.graphql")
graphqlSourceDirectorySet.exclude("**/schema.graphql")
}
For documentation on those options, see https://www.apollographql.com/docs/android/essentials/plugin-configuration/
To summarize: for the JS GraphQL plugin, which you want in order to easily work with graphql files, you need the schema.graphql which you download from the .graphqlconfig. For Apollo Android, you need the schema.json, which you download using the Apollo cli interface.
[Edit June 2020] For Apollo Android 2, you can use the new Gradle plugin, so the complete build.gradle.kts becomes as follows:
Remember to always check for dependency updates before using, for example using the help/useLatestVersions Gradle task from the use-latest-versions Gradle plugin.
plugins {
val kotlinVersion = "1.3.72"
application
kotlin("jvm") version kotlinVersion
java
idea
// Plugin which checks for dependency updates with help/dependencyUpdates task.
id("com.github.ben-manes.versions") version "0.28.0"
// Plugin which can update Gradle dependencies, use help/useLatestVersions
id("se.patrikerdes.use-latest-versions") version "0.2.14"
id("com.apollographql.apollo") version "2.1.0"
}
dependencies {
implementation(kotlin("stdlib"))
// Apollo and dependencies
implementation("com.apollographql.apollo:apollo-runtime:2.1.0")
implementation("com.squareup.okio:okio:2.4.3")
implementation("org.jetbrains:annotations:19.0.0")
testImplementation("org.jetbrains:annotations:19.0.0")
}
repositories {
mavenCentral()
mavenLocal()
jcenter()
}
apollo {
generateKotlinModels.set(true)
graphqlSourceDirectorySet.srcDir("src/main/graphql")
graphqlSourceDirectorySet.include("**/*.graphql")
graphqlSourceDirectorySet.exclude("**/schema.graphql")
}
tasks.withType<org.jetbrains.kotlin.gradle.tasks.KotlinCompile> {
kotlinOptions.jvmTarget = "1.8"
}

idea plugin gradle wrong iml file used

Hi I try to setup my intelliJ with gradle.
IntelliJ creates and uses a project.iml in the .idea\modules directory.
When I use gradle with the idea plugin it generates a project.iml in the projects root directory. How can I convince the gradle plugin to use right iml file?
idea {
module {
iml {
withXml {
println "== IDEA with Xml =="
def moduleRoot = it.asNode()
def facetManager = moduleRoot.component.find { component -> component.'#name' == 'FacetManager' }
if (!facetManager) {
println "== new Facet Manager =="
facetManager = moduleRoot.appendNode('component', [name: 'FacetManager'])
}
/* ---------------------------------------------------------------------------------------------------- */
def oldSpringFacet = facetManager.facet.find { facet -> facet.'#type' == 'Spring' && facet.'#name' == 'Spring' }
if (oldSpringFacet){
println "== Replacing Spring Facet =="
facetManager.remove oldSpringFacet
}
def builder = new NodeBuilder()
def springFacet = builder.facet(type: 'Spring', name: 'Spring') {
configuration {
fileset(id: 'fileset', name: 'Spring Application Context', removed: 'false') {
file('file://$MODULE_DIR$/../../src/main/resources/spring/ApplicationContext.xml'){}
file('file://$MODULE_DIR$/../../src/main/resources/spring/local.ApplicationContext.extensions.xml'){}
file('file:// }
}
}
facetManager.append springFacet
...
I use Gradle 3.5 and IntelliJ 2017.1.4
Got this tip in a comment, but the comment disappeared:
This article How to import build.gradle into IntelliJ
says that the idea plugin is not longer supported. Therefore it is not recommended to use it :-(