embedding maven into OSGi application - osgi

I am trying to call MavenCli from my OSGi plugin project. I have added the correct libraries to my build path and to the manifest. I believe that I have done everything correct so far because when I add a main method to the class that calls maven and run it in eclipse, everything works as expected. When I run it from my OSGi plugin, I get the following error (with the maven switches -X -e):
Apache Maven 3.0-beta-1 (r935667; 2010-04-19 10:00:39-0700)
Java version: 1.6.0_16
Java home: C:\Java\jdk1.6.0_16\jre
Default locale: en_US, platform encoding: Cp1252
OS name: "windows 7" version: "6.1" arch: "amd64" Family: "windows"
[INFO] Error stacktraces are turned on.
[ERROR] Error executing Maven.
org.codehaus.plexus.component.repository.exception.ComponentLookupException: Component descriptor cannot be found in the component repository
role: org.apache.maven.Maven
roleHint:
classRealm: none specified
at org.codehaus.plexus.DefaultComponentRegistry.getComponentManager(DefaultComponentRegistry.java:435)
at org.codehaus.plexus.DefaultComponentRegistry.getComponent(DefaultComponentRegistry.java:353)
at org.codehaus.plexus.DefaultComponentRegistry.lookup(DefaultComponentRegistry.java:178)
at org.codehaus.plexus.DefaultPlexusContainer.lookup(DefaultPlexusContainer.java:383)
at org.apache.maven.cli.MavenCli.container(MavenCli.java:363)
at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:156)
at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:131)
I am using maven 3, beta 1, and using the following method call:
int x = MavenCli.doMain(params.toArray(new String[] {}), null);
where params contains things like "compile", etc.
Any ideas? Thanks.

I got this working by passing passing a classloader (this.getClass().getClassLoader()) to a DefaultContainerConfiguration and passing my DefaultContainerConfiguration to a DefaultPlexusContainer. Using the plexus, I was able to load instantiate a MavenExecutionRequestPopulator and a Maven object.
Then when I try to execute any goals, I create a MavenExecutionRequest and set the Pom file, system and user properties. The system properties are obtained from the System and have my -Dfoo=x properties, etc.
After that, I use a method I shamelessly stole (cant remember from where), but adapted a little ...
public MavenExecutionResult execute(MavenExecutionRequest request) {
if (request == null) {
return null;
}
MavenExecutionResult result;
try {
populator.populateDefaults(request);
result = maven.execute(request);
} catch (MavenExecutionRequestPopulationException ex) {
ex.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
Let me know if any further details are required. I would post all the code, but it is spread over numerous files. Good luck.

Related

Using Avro to java plugin in gradle kotlin dsl

I've a java project that is built using gradle kotlin dsl.
Now I want to use gradle-avro-plugin like this https://github.com/davidmc24/gradle-avro-plugin#alternate-usage
In kotlin dsl I have written the same logic as below -
plugins {
java
id( "com.github.davidmc24.gradle.plugin.avro") version "1.0.0"
}
dependencies {
implementation ("org.apache.avro", "avro", "1.10.1")
}
val generateAvro = tasks.register<com.github.davidmc24.gradle.plugin.avro.GenerateAvroJavaTask>("generateAvro") {
source("src/avro")
this.setOutputDir(file("dest/avro"))
}
configure<org.gradle.api.tasks.compile.JavaCompile> {
this.source = fileTree(generateAvro)
}
The above code is returning below error when I run grade compileJava-
> * What went wrong:
Extension of type 'JavaCompile' does not exist. Currently registered extension types: [ExtraPropertiesExtension, DefaultArtifactPublicationSet, SourceSetContainer, ReportingExtension, JavaPluginExtension, JavaInstallationRegistry, JavaToolchainService, DistributionContainer, JavaApplication, DefaultAvroExtension]
How can I fix this error?
I had similar issues, what worked for me was:
plugins {
id("com.github.davidmc24.gradle.plugin.avro") version "1.2.0"
}
dependencies {
implementation("org.apache.avro:avro:1.10.1")
}
tasks.withType<com.github.davidmc24.gradle.plugin.avro.GenerateAvroJavaTask> {
setOutputDir(file("src/dest/dir/"))
}
The important thing is I did not registered a new task, just specified a new destination directory for each task with the type GenerateAvroJavaTask

JAVAFX environmental variable return null in build.gradle.kts

I am using following build.gradle.kts for JavaFX app
plugins {
kotlin("jvm") version "1.4.30"
id("application")
id("org.openjfx.javafxplugin") version "0.0.9"
}
repositories {
mavenCentral()
}
javafx {
version = "11"
modules("javafx.controls", "javafx.fxml")
sdk = System.getenv("JAVAFX")
if (sdk == null || sdk2.isBlank()) {
throw InvalidUserDataException("JAVAFX environment variable is not set. JAVAFX = $sdk")
}
application {
mainClass.set("example.Main")
applicationName = "Main"
applicationDefaultJvmArgs = listOf(
"--module-path=${sdk}${File.separator}lib",
"--add-modules=javafx.controls,javafx.fxml" )
println("applicationDefaultJvmArgs:$applicationDefaultJvmArgs")
}
}
dependencies {
implementation(kotlin("stdlib"))
}
I have set environmental variable in .bashrc like below
export JAVAFX=$HOME/path/to/JavaFX/SDK
when I execute echo $JAVAFX I get the JavaFX SDK path but still I am getting null in build.gradle.kts
Tried restarting IntelliJ idea too, still the same.
Out-of-the-box, Gradle will spawn a Java process in the background. Typically this is the Gradle Daemon, but there may be more.
So to ensure new environment variables are seen, it's best to kill any Java process that are running in the background. Depending on your system, open up task manager and kill and lingering Java process.

NoClassDefFoundError: java.sql.Date when running Play 2.6 using gradle plugin

Has anyone had much luck with the play gradle plugin? I'm trying to run the Play Framework 2.6 starter project. I can run from SBT fine but I get the following error when I run from gradle:
play.api.UnexpectedException: Unexpected exception[NoClassDefFoundError: java/sql/Date]
at play.core.server.DevServerStart$$anon$1.reload(DevServerStart.scala:190)
at play.core.server.DevServerStart$$anon$1.get(DevServerStart.scala:124)
at play.core.server.AkkaHttpServer.handleRequest(AkkaHttpServer.scala:202)
at play.core.server.AkkaHttpServer.$anonfun$createServerBinding$1(AkkaHttpServer.scala:117)
at akka.stream.impl.fusing.MapAsync$$anon$25.onPush(Ops.scala:1194)
at akka.stream.impl.fusing.GraphInterpreter.processPush(GraphInterpreter.scala:519)
at akka.stream.impl.fusing.GraphInterpreter.processEvent(GraphInterpreter.scala:482)
at akka.stream.impl.fusing.GraphInterpreter.execute(GraphInterpreter.scala:378)
at akka.stream.impl.fusing.GraphInterpreterShell.runBatch(ActorGraphInterpreter.scala:
I'm using Java 1.8 with the following build.gradle:
plugins {
id 'play'
id 'idea'
}
def playVersion = "2.6.13"
def scalaVersion = System.getProperty("scala.binary.version", /* default = */ "2.12")
model {
components {
play {
platform play: playVersion, scala: scalaVersion, java: '1.8'
injectedRoutesGenerator = true
sources {
twirlTemplates {
defaultImports = TwirlImports.JAVA
}
}
}
}
}
dependencies {
play "com.typesafe.play:play-guice_$scalaVersion:$playVersion"
play "com.typesafe.play:play-logback_$scalaVersion:$playVersion"
play "com.h2database:h2:1.4.196"
playTest "org.assertj:assertj-core:3.6.2"
playTest "org.awaitility:awaitility:2.0.0"
}
repositories {
jcenter()
maven {
name "lightbend-maven-releases"
url "https://repo.lightbend.com/lightbend/maven-release"
}
ivy {
name "lightbend-ivy-release"
url "https://repo.lightbend.com/lightbend/ivy-releases"
layout "ivy"
}
}
You need to set up the java_home to use a Java 1.8 version. Apparently, the play gradle plugin expects a java home.
export JAVA_HOME=YOUR_JAVA_LOCATION
$ source .bash_profile
$ echo $JAVA_HOME
I found out the issue, my $JAVA_HOME was set to my Java 9 path but java/javac were set to Java 8. This was causing my gradle to use the wrong java version. After fixing my $JAVA_HOME, it works correctly.
I'll leave this up in case anyone else runs into this issue.

wsdl2java using Axis 1.4 in Gradle

I searched for plugins and tutorials but neither of them worked in the given context:
I'd like to generate server-side Java classes from a list of given WSDL files. They have to be generated with Axis 1.4 and Java 1.7.
My half-working code is the following:
configurations {
axisGenAntTask
}
task genWsdlClasses() {
doLast {
def wsdlDir = file(axisInputDir)
def wsdlFiles = new FileNameByRegexFinder().getFileNames("${wsdlDir}", /.*\.wsdl/)
wsdlFiles.each { String wsdlFile ->
ant.echo(message: "Generating Classes for use with WSDL")
ant.taskdef(
name: "genClassesFromWSDL",
classname: "org.apache.axis.tools.ant.wsdl.Wsdl2javaAntTask",
classpath: configurations.axisGenAntTask.asPath
)
ant.genClassesFromWSDL(
url: wsdlFile,
output: file(cxfOutputDir)
)
}
}
}
tasks.withType(JavaCompile) {
dependsOn genWsdlClasses
}
dependencies {
axisGenAntTask "org.apache.axis:axis-ant:1.4",
"org.apache.axis:axis:1.4",
"org.apache.axis:axis-jaxrpc:1.4",
"axis:axis-wsdl4j:1.5.1",
"commons-codec:commons-codec:1.3",
"commons-logging:commons-logging:1.1.1",
"commons-discovery:commons-discovery:0.2"
}
However, a generated CustomException class doesn't extend Exception, thus it is not throwable and Java code compilation isn't working (see similar question here: Exception classes generated using Axis2 wsdl2java don't extend Exception).
Somehow I would just have to tell ant.taskdef not to "unpack" the classes, as I read in the referenced SO-question, but the mentioned arguments are from Axis 2, not from the needed Axis 1.4 though.

custom gradle plugin causes: Cannot configure the 'publishing' extension

I have a custom gradle plugin in which custom task types and gradle configurations are added. When I apply this plugin before maven-publish it works perfectly fine. But when I add it after apply plugin: 'maven-publish', it fails with error message :
FAILURE: Build failed with an exception.
* Where:
Build file '/scratch/skgupta/git_storage/emdi/integtest/build.gradle' line: 38
* What went wrong:
A problem occurred evaluating root project 'integtest'.
> Cannot configure the 'publishing' extension after it has been accessed.
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.
BUILD FAILED
Total time: 7.6 secs
Here is the build.gradle file.
buildscript {
repositories {
maven {
url = "${artifactory_contextUrl}/repo"
}
}
dependencies {
classpath group: 'com.mycomp.proj', name: 'MyCustomPlugin', version: "${pluginVersion}", transitive: true
}
}
apply plugin: 'java'
apply plugin: 'maven-publish'
apply plugin: 'MyCustomPlugin' // WHen this line is moved above maven-publish, build works fine.
// add jar name and version
jar.archiveName='lrgemaas_small_deploy_3n.jar'
group = 'com.mycom.proj.test'
version = '1.0.3'
dependencies {
compile group: 'eaas.platform', name: 'registry-lookup-client', version: '0.1'
compile group: 'eaas.platform', name: 'registry-client', version: '0.1'
compile configurations.lrgConfig // This configuration is added by MyCustomPlugin
compile configurations.webdriver // This configuration is added by MyCustomPlugin
}
repositories {
maven {
url = "${artifactory_contextUrl}/repo"
}
}
publishing {
publications {
myPublicationName(MavenPublication) {
artifactId 'lrgemaas_small_deploy_3n'
artifact jar.archivePath
}
}
repositories {
maven {
url = "${artifactory_contextUrl}/${artifactory_repoName}"
credentials {
username = "${artifactory_user}"
password = "${artifactory_password}"
}
}
}
}
// workflow for build
defaultTasks 'clean','build','publish'
PS: I tried doing nothing in the custom plugin (i.e., simply return from apply method), but it still gives same error.
Simply replacing:
publishing {
publications {
...
}
}
with following:
publishing.publications {
...
}
worked for me!
Gradle is brittle regarding the order of the plugins. There is a discussion about this exact issue at
https://discuss.gradle.org/t/apply-maven-publish-plugin-from-init-script/2460
"Cool, so this is what happens.
DefaultPublishingExtension which is backing the 'publishing {}' block is a DeferredConfigurable. It's a mechanism that allows to register a configuration block to be executed when an extension is accessed. Unfortunately sometimes it causes unexpected behaviour if you access this kind of extension unawares. This is exactly the case when for example you try to get all the properties of a project (as the release plugin does here: https://github.com/townsfolk/gradle-release/blob/master/src/main/groovy/release/PluginHelper.groovy#L230"
FYI, I use a dynamic version and found that I had to define version prior to apply of my plugins. Probably because java or maven-publish sets the publication details upon application.
I upgraded gradle version from 2.1 to 2.12 and it solved this problem, fwiw.

Resources