How to debug "java.lang.NullPointerException: getService(T::class.java)" in official Kotlin template of IntelliJ IDEA plugin?

Answered

My plugin is based on official Jet Brains Kotlin template. Currently I am sharing only Live Templates via this plugn, so I have not touch anything below IDEsPlugins/IntelliJ_IDEA/src/main/kotlin (well, I have not Kotlin experience, but I need to develop the plugins).

When I run the plugin in test mode, I get:

java.lang.RuntimeException: java.lang.NullPointerException: getService(T::class.java) must not be null
    at com.intellij.openapi.application.impl.LaterInvocator.invokeAndWait(LaterInvocator.java:118)
    at com.intellij.openapi.application.impl.ApplicationImpl.invokeAndWait(ApplicationImpl.java:505)
    at com.intellij.openapi.application.impl.ApplicationImpl.invokeAndWait(ApplicationImpl.java:525)
    at com.intellij.openapi.project.impl.ProjectManagerExImplKt.openProject(ProjectManagerExImpl.kt:618)
    at com.intellij.openapi.project.impl.ProjectManagerExImplKt.access$openProject(ProjectManagerExImpl.kt:1)
    at com.intellij.openapi.project.impl.ProjectManagerExImpl$doOpenAsync$1.invoke(ProjectManagerExImpl.kt:149)
    at com.intellij.openapi.project.impl.ProjectManagerExImpl$doOpenAsync$1.invoke(ProjectManagerExImpl.kt:60)
    // ...

I apended the full output.

More output of Run Plugin task:


1: Task failed with an exception.
-----------
* What went wrong:
Execution failed for task ':runIde'.
> Build cancelled while executing task ':runIde'

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
==============================================================================

2: Task failed with an exception.
-----------
* What went wrong:
Execution failed for task ':classpathIndexCleanup'.
> Build cancelled while executing task ':classpathIndexCleanup'

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
==============================================================================

* Get more help at https://help.gradle.org

BUILD FAILED in 1m 42s

If to try to search getService in whole project, no search results will be.

If to check some classes like MyProjectManagerListener, in each one there are some errors.
For example, in MyProjectManagerListener:

internal class MyProjectManagerListener : ProjectManagerListener {

    override fun projectOpened(project: Project) {
        project.service<MyProjectService>()
    }
}

there is the error:

Cannot access 'java.util.EventListener' which is a supertype of 'com.github.tokugawatakeshi.temp.listeners.MyProjectManagerListener'.

In MyBundle:

object MyBundle : DynamicBundle(BUNDLE) {

    @Suppress("SpreadOperator")
    @JvmStatic
    fun message(@PropertyKey(resourceBundle = BUNDLE) key: String, vararg params: Any) =
        getMessage(key, *params)

    @Suppress("SpreadOperator", "unused")
    @JvmStatic
    fun messagePointer(@PropertyKey(resourceBundle = BUNDLE) key: String, vararg params: Any) =
        getLazyMessage(key, *params)
}

there are the errors like:

Cannot access class 'java.lang.String'.

Let me repeat that I have not touch the boilerplate Kotilin code in src/main/kotlin.

I understand that I need to do some efforts myself, but currently I have no idea what exactly I need to do.

The plugin's repository (if you are going to clone it for investigations please checkout the @v2.0 branch)

 

 

0
8 comments

Sorry for delay. You can remove all unneeded sample code from the template of course, see https://github.com/JetBrains/intellij-platform-plugin-template/#sample-code

1

Please check that "Gradle JVM" setting in Preferences | Build, Execution, Deployment | Build Tools | Gradle points to Java **11** installation.

Also update Gradle IntelliJ Plugin version to latest (1.9.0) in IDEsPlugins/IntelliJ_IDEA/build.gradle.kts line 12.

 

PS: Please make sure to post plugin development questions to " IntelliJ IDEA Open API and Plugin Development" forum, Thanks.

0

Yann Cebron

Thank you for the answer. 

I checked the Preferences | Build, Execution, Deployment | Build Tools | Gradle. The Gradle JVM is pointing to Project SDK 11.

The Project SDK is currently 11 java version 11.0.3. I'll also show which other versions are available.

About plugin version: I always keep the plugins up-date and currently the Gradle plugin has build version 222.4167.29.

0

Please check your plugin's module in Project Settings->Modules has also proper Java 11 and language level set.

Also please keep Gradle version itself always up-to-date (7.5.1 currently), change in gradle/wrapper/gradle-wrapper.properties#L3

0

Yann Cebron

Report about my actions in details. I apologize in advance about long post, but please understand that I am trying to cooperate as possible.

First, I am sorry about I have missed 

update Gradle IntelliJ Plugin version to latest (1.9.0) in IDEsPlugins/IntelliJ_IDEA/build.gradle.kts 

step. I have finished this step now, and now my build.gradle.kts is:

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

fun properties(key: String) = project.findProperty(key).toString()

plugins {
// Java support
id("java")
// Kotlin support
id("org.jetbrains.kotlin.jvm") version "1.7.10"
// Gradle IntelliJ Plugin
id("org.jetbrains.intellij") version "1.9.0"
// Gradle Changelog Plugin
id("org.jetbrains.changelog") version "1.3.0"
// Gradle Qodana Plugin
id("org.jetbrains.qodana") version "0.1.12"
}

group = properties("pluginGroup")
version = properties("pluginVersion")

// Configure project's dependencies
repositories {
mavenCentral()
}

// Configure Gradle IntelliJ Plugin - read more: https://github.com/JetBrains/gradle-intellij-plugin
intellij {
pluginName.set(properties("pluginName"))
version.set(properties("platformVersion"))
type.set(properties("platformType"))
downloadSources.set(properties("platformDownloadSources").toBoolean())
updateSinceUntilBuild.set(true)

// Plugin Dependencies. Uses `platformPlugins` property from the gradle.properties file.
plugins.set(properties("platformPlugins").split(',').map(String::trim).filter(String::isNotEmpty))
}

// Configure Gradle Changelog Plugin - read more: https://github.com/JetBrains/gradle-changelog-plugin
changelog {
version.set(properties("pluginVersion"))
groups.set(emptyList())
}

// Configure Gradle Qodana Plugin - read more: https://github.com/JetBrains/gradle-qodana-plugin
qodana {
cachePath.set(projectDir.resolve(".qodana").canonicalPath)
reportPath.set(projectDir.resolve("build/reports/inspections").canonicalPath)
saveReport.set(true)
showReport.set(System.getenv("QODANA_SHOW_REPORT").toBoolean())
}

tasks {
// Set the JVM compatibility versions
properties("javaVersion").let {
withType<JavaCompile> {
sourceCompatibility = it
targetCompatibility = it
}
withType<KotlinCompile> {
kotlinOptions.jvmTarget = it
}
}

wrapper {
gradleVersion = properties("gradleVersion")
}

patchPluginXml {
version.set(properties("pluginVersion"))
sinceBuild.set(properties("pluginSinceBuild"))
untilBuild.set(properties("pluginUntilBuild"))

// Extract the <!-- Plugin description --> section from README.md and provide for the plugin's manifest
pluginDescription.set(
projectDir.resolve("README.md").readText().lines().run {
val start = "<!-- Plugin description -->"
val end = "<!-- Plugin description end -->"

if (!containsAll(listOf(start, end))) {
throw GradleException("Plugin description section not found in README.md:\n$start ... $end")
}
subList(indexOf(start) + 1, indexOf(end))
}.joinToString("\n").run { markdownToHTML(this) }
)

// Get the latest available change notes from the changelog file
changeNotes.set(provider {
changelog.run {
getOrNull(properties("pluginVersion")) ?: getLatest()
}.toHTML()
})
}

runPluginVerifier {
ideVersions.set(properties("pluginVerifierIdeVersions").split(',').map(String::trim).filter(String::isNotEmpty))
}

// Configure UI tests plugin
// Read more: https://github.com/JetBrains/intellij-ui-test-robot
runIdeForUiTests {
systemProperty("robot-server.port", "8082")
systemProperty("ide.mac.message.dialogs.as.sheets", "false")
systemProperty("jb.privacy.policy.text", "<!--999.999-->")
systemProperty("jb.consents.confirmation.enabled", "false")
}

signPlugin {
certificateChain.set(System.getenv("CERTIFICATE_CHAIN"))
privateKey.set(System.getenv("PRIVATE_KEY"))
password.set(System.getenv("PRIVATE_KEY_PASSWORD"))
}

publishPlugin {
dependsOn("patchChangelog")
token.set(System.getenv("PUBLISH_TOKEN"))
// pluginVersion is based on the SemVer (https://semver.org) and supports pre-release labels, like 2.1.7-alpha.3
// Specify pre-release label to publish the plugin in a custom Release Channel automatically. Read more:
// https://plugins.jetbrains.com/docs/intellij/deployment.html#specifying-a-release-channel
channels.set(listOf(properties("pluginVersion").split('-').getOrElse(1) { "default" }.split('.').first()))
}
}

Unfortunately, I still have a lot of errors messages:

The Run IDE for UI Tests task is being executed now, but only until try to open some project:

Following your instructions, I have checked the Project Settings->Modules. The Language level is 11:

 

Finally, I have update the the line 3 in gradle/wrapper/gradle-wrapper.properties. Now it is:

distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.5.1-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

Nothing changes even after the background tasks has finished.

 

In this Youtrack issue, the removing of .idea and .gradle directories has been advised. I have done this, and above errors has been disappeared, however the main error - java.lang.NullPointerException: getService(T::class.java) is still occurs if to run Run IDE for UI Tests.

When I reopened the project after deleting of .idea and .gradle, the Project settings has been updated to:

and Modules settings has been updated to:

The newest output:

2022-10-11 12:40:48,687 [   2800]   WARN - #c.i.n.i.NotificationGroupManagerImpl - Notification group CodeWithMe is already registered (group=com.intellij.notification.NotificationGroup@3738a395). Plugin descriptor: PluginDescriptor(name=Code With Me, id=com.jetbrains.codeWithMe, descriptorPath=plugin.xml, path=~\.gradle\caches\modules-2\files-2.1\com.jetbrains.intellij.idea\ideaIC\2022.2\42c296374014a649785bb84aa6d8dc2d18f2ca0e\ideaIC-2022.2\plugins\cwm-plugin, version=222.3345.118, package=null, isBundled=true)
Info  | RdCoroutineScope          | 45:JobScheduler FJ pool 13/15 | RdCoroutineHost overridden 
2022-10-11 12:41:07,199 [  21312] SEVERE - #c.i.o.p.i.ProjectFrameAllocator - java.lang.NullPointerException: getService(T::class.java) must not be null
java.lang.RuntimeException: java.lang.NullPointerException: getService(T::class.java) must not be null
    at com.intellij.openapi.application.impl.LaterInvocator.invokeAndWait(LaterInvocator.java:118)
    at com.intellij.openapi.application.impl.ApplicationImpl.invokeAndWait(ApplicationImpl.java:505)
    at com.intellij.openapi.application.impl.ApplicationImpl.invokeAndWait(ApplicationImpl.java:525)
    at com.intellij.openapi.project.impl.ProjectManagerExImplKt.openProject(ProjectManagerExImpl.kt:618)
    at com.intellij.openapi.project.impl.ProjectManagerExImplKt.access$openProject(ProjectManagerExImpl.kt:1)
    at com.intellij.openapi.project.impl.ProjectManagerExImpl$doOpenAsync$1.invoke(ProjectManagerExImpl.kt:149)
    at com.intellij.openapi.project.impl.ProjectManagerExImpl$doOpenAsync$1.invoke(ProjectManagerExImpl.kt:60)
    at com.intellij.openapi.project.impl.ProjectUiFrameAllocator$run$progressRunner$1.apply(ProjectFrameAllocator.kt:95)
    at com.intellij.openapi.project.impl.ProjectUiFrameAllocator$run$progressRunner$1.apply(ProjectFrameAllocator.kt:71)
    at com.intellij.openapi.progress.impl.ProgressRunner.lambda$submit$3(ProgressRunner.java:252)
    at com.intellij.openapi.progress.impl.CoreProgressManager.lambda$runProcess$2(CoreProgressManager.java:188)
    at com.intellij.openapi.progress.impl.CoreProgressManager.lambda$executeProcessUnderProgress$12(CoreProgressManager.java:608)
    at com.intellij.openapi.progress.impl.CoreProgressManager.registerIndicatorAndRun(CoreProgressManager.java:683)
    at com.intellij.openapi.progress.impl.CoreProgressManager.computeUnderProgress(CoreProgressManager.java:639)
    at com.intellij.openapi.progress.impl.CoreProgressManager.executeProcessUnderProgress(CoreProgressManager.java:607)
    at com.intellij.openapi.progress.impl.ProgressManagerImpl.executeProcessUnderProgress(ProgressManagerImpl.java:60)
    at com.intellij.openapi.progress.impl.CoreProgressManager.runProcess(CoreProgressManager.java:175)
    at com.intellij.openapi.progress.impl.ProgressRunner.lambda$submit$4(ProgressRunner.java:252)
    at java.base/java.util.concurrent.CompletableFuture$AsyncSupply.run(CompletableFuture.java:1768)
    at java.base/java.util.concurrent.CompletableFuture$AsyncSupply.exec(CompletableFuture.java:1760)
    at java.base/java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:373)
    at java.base/java.util.concurrent.ForkJoinPool$WorkQueue.topLevelExec(ForkJoinPool.java:1182)
    at java.base/java.util.concurrent.ForkJoinPool.scan(ForkJoinPool.java:1655)
    at java.base/java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1622)
    at java.base/java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:165)
Caused by: java.lang.NullPointerException: getService(T::class.java) must not be null
    at com.github.tokugawatakeshi.temp.listeners.MyProjectManagerListener.projectOpened(MyProjectManagerListener.kt:15)

 

0

About the NullPointer:
1) com.github.tokugawatakeshi.temp.listeners.MyProjectManagerListener is wrongly registered under <applicationListeners> in plugin.xml, it must be under <projectListeners> https://plugins.jetbrains.com/docs/intellij/plugin-listeners.html
2) The requested service from listener com.github.tokugawatakeshi.temp.services.MyProjectService is not registered in any way, and thus fails and returns null https://plugins.jetbrains.com/docs/intellij/plugin-services.html

About IDE issues, please use latest 2022.2 or try 2022.3 EAP. It looks like a Kotlin/Gradle issue or possible misconfiguration on your machine.

0

Yann Cebron

Thank you for the investigations.

First: why these listeners/services are need to be specified in plugin.xml even for live templates-only plugin?
Currently my plugin includes live templates only, and there is no instructions about
listeners and services in the official guide.

Well, I need to finish with plugin realize.

Following your instructions, I have replaced applicationListeners with projectListeners.

<projectListeners>
  <listener class="com.github.tokugawatakeshi.temp.listeners.MyProjectManagerListener"
                    topic="com.intellij.openapi.project.ProjectManagerListener"/>
</projectListeners>

About service, according the documentation, the interface and implementation must be species:

<applicationService
    serviceInterface="mypackage.MyApplicationService"
    serviceImplementation="mypackage.MyApplicationServiceImpl"/>

<projectService
  serviceInterface="mypackage.MyProjectService"
    serviceImplementation="mypackage.MyProjectServiceImpl"/>

Currently, I have no any interfaces and I have not touched the Listeners after retrieved the project template.


internal class MyProjectManagerListener : ProjectManagerListener {

    override fun projectOpened(project: Project) {
        project.service<MyProjectService>()
    }
}


class MyApplicationService {

    init {
        println(MyBundle.message("applicationService"))
    }
}


class MyProjectService(project: Project) {

    init {
        println(MyBundle.message("projectService", project.name))
    }
}
```

How I should fill the serviceInterface attribute?

Currently, my plugin.xml is


<idea-plugin>

    <name>Yamato-Daiwa Frontend</name>
    <vendor url="https://github.com/TokugawaTakeshi" email="tokugawa.takesi@gmail.com">Takeshi Tokugawa</vendor>

    <depends>com.intellij.modules.platform</depends>

    <extensions defaultExtensionNs="com.intellij">

        <defaultLiveTemplates file="liveTemplates/Yamato Daiwa Frontend - Pug.xml"/>
        <defaultLiveTemplates file="liveTemplates/Yamato Daiwa Frontend - Stylus.xml"/>
        <defaultLiveTemplates file="liveTemplates/Yamato Daiwa Frontend - Vue_TypeScript.xml"/>

        <projectService
            serviceInterface="com.github.tokugawatakeshi.temp.services.MyApplicationService"
            serviceImplementation="com.github.tokugawatakeshi.temp.services ???"/>

        <projectService
            serviceInterface="com.github.tokugawatakeshi.temp.services.MyProjectService"
            serviceImplementation="com.github.tokugawatakeshi.temp.services ???"/>

    </extensions>


    <projectListeners>
        <listener class="com.github.tokugawatakeshi.temp.listeners.MyProjectManagerListener"
                  topic="com.intellij.openapi.project.ProjectManagerListener"/>
    </projectListeners>

</idea-plugin>
0

Yann Cebron

Thank you for the support!

Thanks to your help, I finally have published my plugin!

0

Please sign in to leave a comment.