Migrate java class to Kotlin - Cannot resolve symbol annotate class - kotlin

Android Studio 3.4.2
build.gradle:
buildscript {
ext.kotlin_version = '1.3.41'
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.4.2'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
in app/build.gradle:
def AAVersion = '4.6.0'
def KOTLIN_COROUTINE_VERSION = '1.2.1'
dependencies {
annotationProcessor "org.androidannotations:androidannotations:$AAVersion"
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
implementation('com.crashlytics.sdk.android:crashlytics:2.7.0#aar') { transitive = true; }
implementation 'com.google.android.material:material:1.1.0-alpha07'
implementation 'com.google.code.gson:gson:2.8.5'
implementation "org.androidannotations:androidannotations-api:$AAVersion"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:$KOTLIN_COROUTINE_VERSION"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:$KOTLIN_COROUTINE_VERSION"
}
I has activity (java class) annotate by org.androidannotations.annotations.EActivity
Here snippet:
import android.app.Activity;
import android.os.Bundle;
import org.androidannotations.annotations.EActivity
#EActivity
public class LoginActivity extends Activity {
}
And another java activity (SplashActivity.java) that call this LoginActivity like this:
import android.app.Activity;
import android.os.Bundle;
import org.androidannotations.annotations.EActivity
#EActivity
public class SplashActivity extends Activity {
Intent intent = new Intent(thisActivity, LoginActivity_.class);
startActivity(intent);
Nice it's work fine.
Now I migrate only LoginActivity to Kotlin class (LoginActivity.kt)
like this:
import org.androidannotations.annotations.Background
import org.androidannotations.annotations.EActivity
#EActivity
open class LoginActivity : Activity() {
}
and now SplashActivity.java has compile error in this line:
Intent intent = new Intent(thisActivity, LoginActivity_.class);
error message:
Cannot resolve symbol 'LoginActivity_'
P.S. If I remove "_" than compile success:
Intent intent = new Intent(thisActivity, LoginActivity.class);
But I need to use LoginActivity_

You have to use kapt instead of annotationProcessor to handle Kotlin files. Any annotation processor may or may not correctly handle them; for androidannotations in particular there is documentation on Kotlin support.

Related

Cannot access org.apache.hc.client5.http.utils.URLEncodedUtils in kotlin build script

Why is org.apache.hc unresolved considering the dependency has been added?
package com.blah
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory
// Error seen when import line is uncommented:
// 'Unresolved reference: hc'
// import org.apache.hc.client5.http.utils.URLEncodedUtils <--------
import org.w3c.dom.Element
import org.xml.sax.InputSource
import java.io.FileWriter
import java.io.StringReader
import java.net.URI
import java.util.*
val projectVersion: String by project
val liquibaseVersion: String = "4.13.0"
val liquibaseGradlePluginVersion: String = "2.0.4"
plugins {
java
id("org.springframework.boot") apply false
id("org.liquibase.gradle") apply true
}
dependencies {
implementation(platform(org.springframework.boot.gradle.plugin.SpringBootPlugin.BOM_COORDINATES))
liquibaseRuntime(platform(org.springframework.boot.gradle.plugin.SpringBootPlugin.BOM_COORDINATES))
implementation("org.postgresql:postgresql")
implementation("org.liquibase:liquibase-core:$liquibaseVersion")
implementation("org.liquibase:liquibase-gradle-plugin:$liquibaseGradlePluginVersion")
implementation("org.hibernate:hibernate-core")
implementation("org.springframework.boot:spring-boot-starter-data-jpa")
implementation("com.fasterxml.jackson.core:jackson-core")
implementation("com.fasterxml.jackson.core:jackson-databind")
implementation("com.fasterxml.jackson.dataformat:jackson-dataformat-yaml")
implementation("org.springframework.boot:spring-boot-starter-data-jpa")
// No errors when building the Gradle model during import into IDE
// https://mvnrepository.com/artifact/org.apache.httpcomponents.core5/httpcore5
implementation("org.apache.httpcomponents.core5:httpcore5:5.2.1")
liquibaseRuntime("org.liquibase:liquibase-core:$liquibaseVersion")
liquibaseRuntime("org.postgresql:postgresql")
liquibaseRuntime("org.springframework.boot:spring-boot-starter-data-jpa")
liquibaseRuntime(sourceSets.getByName("main").output)
}
Dependencies declared in the dependencies {} block are added to the classpath of the project, not the classpath of the buildscript.
If you want to use dependencies in a Gradle build script, then there are two options
Use the buildscript {} block in build.gradle(.kts)
// build.gradle.kts
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath("org.apache.httpcomponents.core5:httpcore5:5.2.1")
}
}
plugins {
java
id("org.springframework.boot") apply false
id("org.liquibase.gradle") apply true
}
dependencies {
// project dependencies...
}
Define dependencies in an included build, or buildSrc
// ./buildSrc/build.gradle.kts
plugins {
`kotlin-dsl` // a Kotlin or Java plugin is required, so that 'implementation' is available
}
dependencies {
// dependencies defined here will be available in all of the project's build scripts
implementation("org.apache.httpcomponents.core5:httpcore5:5.2.1")
}

kotlinx-serialization not generating serializer in companion of classes annotated with #Serializable

I'm currently trying to create a parent class that can be serialized but has no own attributes. (They will be added in the inheriting classes)
For some reason there is no serializer()-method being generated.
I checked the following things:
The companion-object-class is available in the jar but is empty. No class header or anything. Just an empty file.
I have the serialization-plugin from JetBrains added to my build.gradle-file.
My class is annotated with the kotlinx.serialization.serializable-annotation.
Thank you for reading my question.
This is the exception:
java.lang.NullPointerException: Cannot invoke "me.trqhxrd.grapesrpg.impl.world.predefined.Void$Companion.serializer()" because "me.trqhxrd.grapesrpg.impl.world.predefined.Void.Companion" is null
at me.trqhxrd.grapesrpg.impl.world.BlockData.<clinit>(BlockData.kt:24) ~[GrapesRPG-1.0-SNAPSHOT-all.jar:?]
... 37 more
These code-snippets might be relevant:
build.gradle
plugins {
id 'org.jetbrains.kotlin.jvm' version '1.6.21'
id 'org.jetbrains.kotlin.plugin.serialization' version '1.6.21'
id 'com.github.johnrengelman.shadow' version '7.1.2'
id 'java'
}
group = 'me.trqhxrd'
version = '1.0-SNAPSHOT'
repositories {
mavenCentral()
maven {
url 'https://hub.spigotmc.org/nexus/content/repositories/snapshots/'
}
maven {
url 'https://repo.codemc.org/repository/maven-public/'
}
maven {
url 'https://maven.wolfyscript.com/repository/public/'
}
maven {
url 'https://mvn.trqhxrd.de/releases'
}
}
dependencies {
testImplementation 'org.jetbrains.kotlin:kotlin-test'
testImplementation 'com.github.seeseemelk:MockBukkit-v1.18:1.24.1'
compileOnly 'org.spigotmc:spigot-api:1.18.2-R0.1-SNAPSHOT'
compileOnly 'org.eclipse.aether:aether-api:1.1.0'
compileOnly 'org.eclipse.aether:aether-spi:1.1.0'
compileOnly 'org.eclipse.aether:aether-connector-basic:1.1.0'
compileOnly 'org.eclipse.aether:aether-transport-file:1.1.0'
compileOnly 'org.eclipse.aether:aether-transport-http:1.1.0'
compileOnly 'org.apache.maven:maven-aether-provider:3.3.9'
compileOnly 'org.apache.maven.resolver:maven-resolver-connector-basic:1.8.0'
compileOnly 'org.jetbrains.exposed:exposed-core:0.38.2'
compileOnly 'org.jetbrains.exposed:exposed-jdbc:0.38.2'
compileOnly 'org.jetbrains.exposed:exposed-dao:0.38.2'
compileOnly 'org.xerial:sqlite-jdbc:3.36.0.3'
compileOnly 'com.zaxxer:HikariCP:5.0.1'
compileOnly 'org.slf4j:slf4j-nop:2.0.0-alpha7'
compileOnly 'org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.6.21'
compileOnly 'org.jetbrains.kotlinx:kotlinx-serialization-json-jvm:1.3.2'
compileOnly 'org.jetbrains.kotlin:kotlin-reflect:1.6.21'
compileOnly 'com.google.guava:guava:31.1-jre'
shadow 'org.bstats:bstats-bukkit:3.0.0'
shadow 'me.trqhxrd:menus:1.2.1'
shadow 'com.wolfyscript.wolfyutils.spigot:wolfyutils-spigot:4.16.1.0'
shadow 'de.tr7zw:item-nbt-api:2.9.2'
shadow 'de.tr7zw:nbt-injector:2.9.2'
}
test {
useJUnitPlatform()
}
compileKotlin {
kotlinOptions.jvmTarget = '1.8'
}
compileTestKotlin {
kotlinOptions.jvmTarget = '1.8'
}
tasks.register('installPlugin', Copy) {
dependsOn 'shadowJar'
from layout.buildDirectory.dir("$buildDir/libs/GrapesRPG-1.0-SNAPSHOT-all.jar")
into layout.buildDirectory.dir("$projectDir/Server/plugins")
}
configurations {
shadow
compile.extendsFrom provided
provided.extendsFrom shadow
}
shadowJar {
relocate 'org.bstats', 'me.trqhxrd.shade.bstats'
configurations = [project.configurations.shadow]
from(project.sourceSets.main.output)
}
The parent class
package me.trqhxrd.grapesrpg.impl.world
import kotlinx.serialization.KSerializer
import kotlinx.serialization.Serializable
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.decodeFromJsonElement
import kotlinx.serialization.json.jsonObject
import me.trqhxrd.grapesrpg.impl.world.predefined.Void
import me.trqhxrd.grapesrpg.util.ModuleKey
import me.trqhxrd.grapesrpg.api.world.BlockData as BlockDataAPI
#Serializable
abstract class BlockData(override val id: ModuleKey) : BlockDataAPI {
companion object {
val registry = mutableMapOf<ModuleKey, Pair<Class<out BlockData>, KSerializer<out BlockData>>>()
val KEY_VOID = ModuleKey("grapes", "void")
init {
registry[KEY_VOID] = Void::class.java to Void.serializer()
}
}
override fun save() = Json.encodeToString(this)
#Suppress("UNCHECKED_CAST")
override fun load(serialized: String) {
val key = Json.decodeFromJsonElement<ModuleKey>(
Json.decodeFromString<JsonObject>(serialized)["id"]!!.jsonObject
)
val serializer = registry[key]!!.second
val d = serializer.deserialize(Json.decodeFromString(serialized))
if (this::class.java.isAssignableFrom(d::class.java)) this.apply(d)
}
override fun apply(data: BlockDataAPI) {
if (!this::class.java.isAssignableFrom(data::class.java))
throw IllegalArgumentException(
"Can't load data from a class isn't assignable from the loading class. " +
"(Required: ${this::class.qualifiedName}, Received: ${data::class.qualifiedName})"
)
}
}
The child class
package me.trqhxrd.grapesrpg.impl.world.predefined
import kotlinx.serialization.Serializable
import me.trqhxrd.grapesrpg.impl.world.BlockData
import org.bukkit.event.block.BlockBreakEvent
import org.bukkit.event.block.BlockPlaceEvent
import org.bukkit.event.player.PlayerInteractEvent
#Serializable
class Void : BlockData(KEY_VOID) {
override fun onClick(event: PlayerInteractEvent) {}
override fun onBreak(event: BlockBreakEvent) {}
override fun onPlace(event: BlockPlaceEvent) {}
}
EDIT 1:
I try to create a new object of the Void-class via the empty constructor.
EDIT 2:
All the dependencies are compileOnly because this is a Minecraft-Plugin and most of the dependencies will be downloaded automatically by the Minecraft-Server. That way my Uber-Jar is smaller...
Well I just gave up and used Gson. If anyone finds an answer that doesn't just avoid the problem by removing the library feel free to post it here and I'll mark it as correct.
Thank you for reading...

Class 'AuthenticationProviderUserPassword' does not implement abstract member public abstract fun authenticate

I am stuck in user authentication with micronaut application
authenticate function not accepting httpRequest param
I'm getting an error
Class 'AuthenticationProviderUserPassword' is not abstract and does not implement abstract member public abstract fun authenticate(authenticationRequest: AuthenticationRequest<(raw) Any!, (raw) Any!>!): Publisher! defined in io.micronaut.security.authentication.Authenticatio
Service:
package example.micronaut.services
import io.micronaut.http.HttpRequest
import io.micronaut.security.authentication.AuthenticationFailed
import io.micronaut.security.authentication.AuthenticationProvider
import io.micronaut.security.authentication.AuthenticationRequest
import io.micronaut.security.authentication.AuthenticationResponse
import io.micronaut.security.authentication.UserDetails
import io.reactivex.Flowable
import org.reactivestreams.Publisher
import java.util.*
import javax.inject.Singleton
#Singleton // <1>
class AuthenticationProviderUserPassword : AuthenticationProvider { // <2>
override fun authenticate(httpRequest: HttpRequest<*>?, authenticationRequest: AuthenticationRequest<*, *>?): Publisher<AuthenticationResponse> {
if (authenticationRequest != null && authenticationRequest.identity != null && authenticationRequest.secret != null) {
if (authenticationRequest.identity == "sherlock" && authenticationRequest.secret == "password") {
return Flowable.just<AuthenticationResponse>(UserDetails(authenticationRequest.identity as String, ArrayList()))
}
}
return Flowable.just<AuthenticationResponse>(AuthenticationFailed())
}
}
My build.gradle
plugins {
id "org.jetbrains.kotlin.jvm" version "1.3.50"
id "org.jetbrains.kotlin.kapt" version "1.3.50"
id "org.jetbrains.kotlin.plugin.allopen" version "1.3.50"
id "com.github.johnrengelman.shadow" version "5.2.0"
id "application"
}
version "0.1"
group "example.micronaut"
repositories {
mavenCentral()
maven { url "https://jcenter.bintray.com" }
}
configurations {
// for dependencies that are needed for development only
developmentOnly
}
dependencies {
implementation platform("io.micronaut:micronaut-bom:$micronautVersion")
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:${kotlinVersion}"
implementation "org.jetbrains.kotlin:kotlin-reflect:${kotlinVersion}"
implementation "io.micronaut:micronaut-runtime"
implementation "javax.annotation:javax.annotation-api"
implementation "io.micronaut:micronaut-http-server-netty"
implementation "io.micronaut:micronaut-http-client"
implementation "io.micronaut:micronaut-security-session"
kapt platform("io.micronaut:micronaut-bom:$micronautVersion")
kapt "io.micronaut:micronaut-inject-java"
kapt "io.micronaut:micronaut-validation"
kaptTest platform("io.micronaut:micronaut-bom:$micronautVersion")
kaptTest "io.micronaut:micronaut-inject-java"
runtimeOnly "com.fasterxml.jackson.module:jackson-module-kotlin:2.9.8"
runtimeOnly "ch.qos.logback:logback-classic:1.2.3"
testImplementation platform("io.micronaut:micronaut-bom:$micronautVersion")
testImplementation "io.micronaut.test:micronaut-test-kotlintest"
testImplementation "io.mockk:mockk:1.9.3"
testImplementation "io.kotlintest:kotlintest-runner-junit5:3.3.2"
implementation 'junit:junit:4.12'
compile "io.micronaut.configuration:micronaut-hibernate-jpa"
compile "io.micronaut.configuration:micronaut-hibernate-validator"
compileOnly "jakarta.persistence:jakarta.persistence-api:2.2.2"
annotationProcessor "io.micronaut.data:micronaut-data-processor:1.0.2"
runtime "com.h2database:h2"
runtime "io.micronaut.configuration:micronaut-jdbc-tomcat"
}
test.classpath += configurations.developmentOnly
mainClassName = "example.micronaut.Application"
test {
useJUnitPlatform()
}
allOpen {
annotation("io.micronaut.aop.Around")
}
compileKotlin {
kotlinOptions {
jvmTarget = '1.8'
//Will retain parameter names for Java reflection
javaParameters = true
}
}
compileTestKotlin {
kotlinOptions {
jvmTarget = '1.8'
javaParameters = true
}
}
shadowJar {
mergeServiceFiles()
}
tasks.withType(JavaExec) {
classpath += configurations.developmentOnly
jvmArgs('-noverify', '-XX:TieredStopAtLevel=1', '-Dcom.sun.management.jmxremote')
}
The docs you are looking at are compatible with more recent versions of the interface than you are using. You appear to be using the one at https://github.com/micronaut-projects/micronaut-security/blob/78169cb6927d10dcc6ebc2f6ecb96efb26b9585b/security/src/main/java/io/micronaut/security/authentication/AuthenticationProvider.java#L39 which is why your code won't compile. 2.0RC1 looks like https://github.com/micronaut-projects/micronaut-security/blob/d5ecfc200cf27bd92ec7ce7b3760f5c264ec2647/security/src/main/java/io/micronaut/security/authentication/AuthenticationProvider.java#L44.

Kotlin Annotation Processor not working? What am I missing?

Recently I've been trying to make a annotation processor through Kotlin but I can't seem to get it to work. Everything compiles and I don't get any errors but when I check the contents of my jar file I don't see the resource I'm trying to create.
I've tried everything for hours and I'm really stuck so just looking for help :/ I do have one random class annotated to see if it would work but no luck.
The annotation class
#Retention(AnnotationRetention.RUNTIME)
#Target(AnnotationTarget.CLASS)
annotation class TestAnnotation
The processor class
#AutoService(TestAnnotation::class)
class TestAnnotationProcessor : AbstractProcessor() {
override fun process(annotations: MutableSet<out TypeElement>, environment: RoundEnvironment): Boolean {
this.processingEnv.filer.createResource(StandardLocation.CLASS_OUTPUT, "", "test.txt")
return true
}
override fun getSupportedSourceVersion() = SourceVersion.RELEASE_8
override fun getSupportedAnnotationTypes() = setOf(TestAnnotation::class.java.canonicalName)
}
My build.gradle.kts
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar
plugins {
java
kotlin("jvm") version "1.3.50"
kotlin("kapt") version "1.3.50"
id("com.github.johnrengelman.shadow") version "5.1.0"
}
group = "com.example.test"
version = "1.0"
repositories {
mavenCentral()
}
dependencies {
implementation(kotlin("stdlib-jdk8"))
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.1")
implementation("com.google.auto.service:auto-service:1.0-rc6")
kapt("com.google.auto.service:auto-service:1.0-rc6")
}
configure<JavaPluginConvention> {
sourceCompatibility = JavaVersion.VERSION_1_8
}
tasks.withType<KotlinCompile> {
kotlinOptions.jvmTarget = "1.8"
}
tasks.withType<ShadowJar> {
dependencies {
exclude(dependency("com.google.auto.service:auto-service:1.0-rc6"))
}
}
In order for your custom annotation processor to work, you will have to use it in your build script dependencies
dependencies {
kapt project(':processor-module') // or what ever your processor's module is named.
//OR
kapt 'gourp:artifact:version' // if your processor is published into a maven repository.
}

Trouble with AppcompatActivity - error: cannot find symbol class AppCompatActivity

Im using udacity to learn android development and I have ran into a problem. there are a few errors that have come up:
error: package android.v7.app does not exist
error: cannot find symbol class AppCompatActivity
error: method does not override or implement a method from a supertype
error: cannot find symbol variable super
error: cannot find symbol method setContentView(int)
error: cannot find symbol class openNumbersList
error: cannot find symbol method startActivity(Intent)
Everything was working fine but I was following a tutorial and noticed that my imports in my Main Activity didn't match with what was on the tutorial so I changed:
import...
to
import android.v7.app.AppCompatActivity;
import android.os.Bundle;
also even before this, AppCompatActivity was in red:
Main Activity:
package com.example.android.miwok;
import android.content.Intent;
import android.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set the content of the activity to use the activity_main.xml layout file
setContentView(R.layout.activity_main);
}
public void openNumbersList(View view){
Intent i = new Intent(this, openNumbersList.class);
startActivity(i);
}
}
gradle:
apply plugin: 'com.android.application'
android {
compileSdkVersion 23
buildToolsVersion '27.0.3'
defaultConfig {
applicationId "com.example.android.miwok"
minSdkVersion 15
targetSdkVersion 23
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'),
'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support.constraint:constraint-layout:1.1.2'
testImplementation 'junit:junit:4.12'
implementation 'com.android.support:appcompat-v7:23.3.0'
implementation 'com.android.support:support-v4:23.3.0'
implementation 'com.android.support:design:23.3.0'
}
hope this helps.
I assume, that you forget to add the dependency to the appcompat support library. Add this to your build.gradle in the app folder:
dependencies {
...
// Add this line
implementation 'artifact com.android.support:appcompat-v7:28.0.0-alpha1'
}
However, you should read other tutorials as well because you will proably face more issues, when you don't know how dependencies work in Android. If you create a fresh project in Android Studio, it will create a runnable app for you which is a good point to start off.
EDIT
I re-read your code and the import is incorrect. It must be
android.support.v7.app.AppCompatActivity
instead of
android.v7.app.AppCompatActivity