Avro generated class: Cannot access class 'Builder'. Check your module classpath for missing or conflicting dependencies - kotlin

Running
val myAvroObject = MyAvroObject.newBuilder()
results in a compilation error:
Cannot access class 'MyAvroObject.Builder'. Check your module classpath for missing or conflicting dependencies
I am able to access other MyAvroObject variables. More precisely, methods such as
val schema = MyAvroObject.getClassSchema()
val decoder = MyAvroObject.getDecoder()
compiles fine. What makes it even stranger is that I can access newBuilder() in my test/ folder, but not in my src/ folder.
Why do I get a compile error when using newBuilder()? Is the namespace of the avro-schema used to generate MyAvroObject of importance?

Check your module classpath generally means, that your dependencies (which you didn't provide) are messed up. One of them should read implementation instead of testImplementation, in order to have the method available in the main source-set, instead of only the test source-set - but this may well have to do with the input classes, the output location of generated classes, or annotations alike #VisibleForTesting (just see what it even generates). Command gradlew can also list the dependencies per configuration. The builder seems to be called org.apache.avro.SchemaBuilder... there's only avro-1.11.0.jar & avro-tools-1.11.0.jar. With the "builder" design pattern, .newBuilder() tries to return inner class Builder.

had the same problem today and was able to solve it by adding the following additional source folder
<sourceDir>${project.basedir}/target/generated-sources/avro</sourceDir>
to the kotlin-maven-plugin.

Related

Intellij running multiple kotlin files inside project, instead the one selected

Learning Kotlin and IntelliJ,
Before yesterday if I wanted to run one single .kt file, it was all good. Many ways to do it.
I was doing various exercises, all in the same file exercises.kt. After finishing a code, I would just transform it into a comment and start the next one in the same file.
After many exercises, I decided to create a .kt file for each one. But, now, when I run a single file for one exercise Intellij is running ALL files inside the project, instead of just the one I selected.
EDIT: Every .kt file got its own main function, some with a class. To run a single file I used different methods. Clicking the play button at the left of the main function, or clicking the play button at the top bar with the current file selected and clicling with the right button on top of the file in the project list and selecting "Run filekt" (Same as Ctrt + shift + F10). Like I said before the change explained it was all good.
Here it is my run configuration:
Content of one of my files that was single running before I changed
fun main() {
val amanda = Person("Amanda", 33, "play tennis", null)
val atiqah = Person("Atiqah", 28, "climb", amanda)
amanda.showProfile()
atiqah.showProfile()
}
class Person(val name: String, val age: Int, val hobby: String?, val referrer: Person?) {
fun showProfile() {
when {
referrer == null -> println("""Name: ${name}
Age: ${age}
Likes to ${hobby}. Doesn't have a referrer."""")
else -> println("""Name: ${name}
Age: ${age}
Likes to ${hobby}. Has a referrer named ${referrer.name}, who likes to ${referrer.hobby}""")
}
}
}
When Intellij run all the files, this is showing in the project errors. This is new as well. If I try to run the SongCatalog files on Kotlin Playground it's all good.(The Special Auction is in progress)
For the rest of the files, here's the repository: Google Learning Repo
IntelliJ does not run all the files. It compiles all the files, but only runs the file that you specified in the run configuration.
However, since two of your files, SongCatalog.kt and SongCatalog2.kt, both declare a SongCatalog class, there is a compiler error. The same class cannot be declared twice, after all. Even if you are just trying to run some other file, all the files in your project has to be compiled.
Using Packages
I recommend just putting each exercise that you are doing in its package. This way the two SongCatalogs are distinct. For example, at the start of SongCatalog.kt, you can write:
package exercise4_1
and at the start of SongCatalog2.kt, you can write:
package exercise4_2
Put each file into a folder with the same name as the package. Do this for all the other files containing your exercises so that it's organised.
Make sure that IntelliJ don't automatically insert imports, importing things from other exercises, causing conflicts again.
Then in your run configuration, write add the package name as a prefix for the main class. For example, to run SongCatalog.kt, you'd write exercise4_1.SongCatalogKt.
Using Modules
There is also another rather overkill method of having IntelliJ only compile a part of your project's files. You can put each of your exercises' files into a different module.
To add a module, go to File -> New -> Module. Then you can give that module a name and add new .kt files to the /src folder of that module.
Configure your run configuration the same way as before, except choose the module that you want to run in the "use class path of module" dropdown.

Use of Gradle Kotlin DSL Jar.from()

I'm trying to include a single source file for the Main-Class of a jar -- actually I have a toplevel directory of such files, demo/, but I don't want them all in a jar. I want separate jars, each using only one of these.
This seems like sort of an anti-pattern in gradle, as the fundamental mechanism infers or prefers that I should instead place each in a distinct sourceSet. Ugh.
A casual reading of the docs implies Jar.from() might be useful this way: "Specifies the source files or directories..."
As it turns out, "source" is perhaps a bit of a misnomer. Here's an example, a typical kotlin fat jar with the added from("demo/LockingBufferDemo.kt"):
val jar by tasks.getting(Jar::class) {
manifest { attributes["Main-Class"] = "LockingBufferDemoKt" }
from(sourceSets.main.get().output)
from("demo/LockingBufferDemo.kt")
dependsOn(configurations.runtimeClasspath)
from({
configurations.runtimeClasspath.get().filter {
it.name.endsWith("jar") }.map { zipTree(it) }
})
}
Forgive my naivety: Guess what does not end up in the jar? LockingBufferDemo.class. Guess what does? LockingBufferDemo.kt. In other words, this is treated more like a resource, not a source, and what would have been the simplest answer is a dead end.
Another way to approach this would be add the demo directory as an independent sourceSet and then use from(sourceSets["demo"].get(), except I can't find a way to complete that; according to IntelliJ get() returns a rather opaque "Provider" which I can't find mentioned in the actual javadoc: 1, 2 and I really feel like I'm heading down the garden path at this point with the woods rapidly growing darker around me.
This should not be this complicated.
How can I add a single file (or class derived from such) into a jar in gradle without having to put it alone in a directory and create a sourceSet for every such directory?
Regarding your explanations at the start of your post, you should consider creating multiple tasks of type Jar on your own, as every task of type Jar will only create a single JAR-file, and you "want separate jars". I do not think you should use different source sets, as all of the files are Java Kotlin source files in the end and are processed in the same way (compilation, tests, docs ...). Multiple source sets would complicate this common pipeline.
"Specifies the source files or directories..." As it turns out, "source" is perhaps a bit of a misnomer.
Well, the documentation does not stop there, but it says "for a copy and creates a child CopySpec". So it is not the source as in source code, but the source of a copy operation. In Gradle, tasks that create an archive (ZIP, JAR) share their API with tasks that copy files, as the creation of an archive can be seen as copying files from their source location to their target location (inside the archive).
So, the from method can be used to specify the files that are copied / archived. But it does not only take a sourcePath parameter, but also a closure or action for configuration. Using this second parameter, you can narrow your source files or directories down to the one file you need, for example using the method include:
val jar by tasks.getting(Jar::class) {
manifest { attributes["Main-Class"] = "LockingBufferDemoKt" }
from(sourceSets.main.get().output) {
include("**/LockingBufferDemo.class")
}
dependsOn(configurations.runtimeClasspath)
from({
configurations.runtimeClasspath.get().filter {
it.name.endsWith("jar") }.map { zipTree(it) }
})
}

How to disable default gradle buildType suffix (-release, -debug)

I migrated a 3rd-party tool's gradle.build configs, so it uses android gradle plugin 3.5.3 and gradle 5.4.1.
The build goes all smoothly, but when I'm trying to make an .aab archive, things got broken because the toolchain expects the output .aab file to be named MyApplicationId.aab, but the new gradle defaults to output MyApplicationId-release.aab, with the buildType suffix which wasn't there.
I tried to search for a solution, but documentations about product flavors are mostly about adding suffix. How do I prevent the default "-release" suffix to be added? There wasn't any product flavor blocks in the toolchain's gradle config files.
I realzed that I have to create custom tasks after reading other questions and answers:
How to change the generated filename for App Bundles with Gradle?
Renaming applicationVariants.outputs' outputFileName does not work because those are for .apks.
I'm using Gradle 5.4.1 so my Copy task syntax reference is here.
I don't quite understand where the "app.aab" name string came from, so I defined my own aabFile name string to match my toolchain's output.
I don't care about the source file so it's not deleted by another delete task.
Also my toolchain seems to be removing unknown variables surrounded by "${}" so I had to work around ${buildDir} and ${flavor} by omitting the brackets and using concatenation for proper delimiting.
tasks.whenTaskAdded { task ->
if (task.name.startsWith("bundle")) { // e.g: buildRelease
def renameTaskName = "rename${task.name.capitalize()}Aab" // renameBundleReleaseAab
def flavorSuffix = task.name.substring("bundle".length()).uncapitalize() // "release"
tasks.create(renameTaskName, Copy) {
def path = "$buildDir/outputs/bundle/" + "$flavorSuffix/"
def aabFile = "${android.defaultConfig.applicationId}-" + "$flavorSuffix" + ".aab"
from(path) {
include aabFile
rename aabFile, "${android.defaultConfig.applicationId}.aab"
}
into path
}
task.finalizedBy(renameTaskName)
}
}
As the original answer said: This will add more tasks than necessary, but those tasks will be skipped since they don't match any folder.
e.g.
Task :app:renameBundleReleaseResourcesAab NO-SOURCE

Kotlin Script Engine throws "unresolved reference", even if the package and class is valid

When using Kotlin's Script Engine, trying to import packages or use any class throws an "unresolved reference"
javax.script.ScriptException: error: unresolved reference: mrpowergamerbr
fun loritta(context: com.mrpowergamerbr.loritta.commands.CommandContext) {
^
This doesn't happen when running the class within IntelliJ IDEA, however it does happen when running the class on production.
While this YouTrack issue is related to fat JARs, this also can happen if you aren't using fat JARs (loading all the libraries via the startup classpath option or the Class-Path manifest option)
To fix this, or you can all your dependencies on your startup script like this:
-Dkotlin.script.classpath=jar1:jar2:jar3:jar4
Example:
java -Dkotlin.script.classpath=libs/dependency1.jar:libs/dependency2.jar:yourjar.jar -jar yourjar.jar
Or, if you prefer, set the property via code, using your Class-Path manifest option.
val path = this::class.java.protectionDomain.codeSource.location.path
val jar = JarFile(path)
val mf = jar.manifest
val mattr = mf.mainAttributes
// Yes, you SHOULD USE Attributes.Name.CLASS_PATH! Don't try using "Class-Path", it won't work!
val manifestClassPath = mattr[Attributes.Name.CLASS_PATH] as String
// The format within the Class-Path attribute is different than the one expected by the property, so let's fix it!
// By the way, don't forget to append your original JAR at the end of the string!
val propClassPath = manifestClassPath.replace(" ", ":") + ":Loritta-0.0.1-SNAPSHOT.jar"
// Now we set it to our own classpath
System.setProperty("kotlin.script.classpath", propClassPath)
While I didn't test this yet, in another unrelated answer it seems you can also supply your own classpath if you initialize the KotlinJsr223JvmLocalScriptEngine object yourself (as seen here)

Grails Currencies Plugin: Unable to resolve class Money

I installed the grails currency plugin. I want to use the Money type in my grails domain class as such:
class FOO{
...
Money lunchCost = new Money(amount:0.00, currency:'USD')
Money dinnerCost = new Money(amount:0.00, currency:'USD')
...
}
I get an error when I compile saying "unable to resolve class Money". I traced the package heirchy of the Grails Money Plugin and tried to put in:
cr.co.arquetipos.currencies.Money breakfastCost = new cr.co.arquetipos.currencies.Money(amount:0.00, currency:'USD')
---- That didn't work either.
1) When I generated Foo, grails placed the domain class under "projectName.Foo" as it does for every domain class created.
2) I'm using Grails 1.3.5.
Do you have any ideas as to where the Currencies class is so I can include it in the
"import <....Money> and get rid of this compilation error?
Same here: The plugin does not integrate with the Grails project, at all. Nevertheless, it has been installed to ${user.home}/.grails/1.3.5/projects/${project.name}/plugins/currencies-0.3.
Since the plugin has been last updated in 2008 and doesn't cover too much functionality, I'd suggest to just copy the two domain classes (in the grails-app/domain folder) into your project.
For an evaluation, you may also want to have a brief look at grails-app/conf and test/integration in the plugin's installation folder.
Like ataylor says, don't use this plugin, it's broken. Instead use JScience. Checkout: Best practice to represent Money (value + currency) in Grails