Amazon AWS KMS + Gradle: NoClassDefFoundError - java

My build.gradle:
apply plugin: 'idea'
apply plugin: 'java'
apply plugin: 'application'
repositories {
mavenCentral()
}
dependencies {
compile 'com.amazonaws:aws-java-sdk:1.11.171'
}
My Java file:
import com.amazonaws.services.kms.AWSKMS;
import com.amazonaws.services.kms.AWSKMSClientBuilder;
import com.amazonaws.services.kms.model.GenerateDataKeyRequest;
import com.amazonaws.services.kms.model.GenerateDataKeyResult;
import java.nio.charset.StandardCharsets;
public class KmsExample {
private static final String KEYID = "arn:aws:kms:us-east-1:[userid]:key/[cmk id]";
public static void main(String[] args) {
AWSKMS kms = AWSKMSClientBuilder.defaultClient();
GenerateDataKeyRequest dataKeyRequest = new GenerateDataKeyRequest();
dataKeyRequest.setKeyId(KEYID);
dataKeyRequest.setKeySpec("AES_128");
GenerateDataKeyResult dataKeyResult = kms.generateDataKey(dataKeyRequest);
String plaintextKey = StandardCharsets.UTF_8.decode(dataKeyResult.getPlaintext()).toString();
String encryptedKey = StandardCharsets.UTF_8.decode(dataKeyResult.getCiphertextBlob()).toString();
System.out.println(plaintextKey + " | " + encryptedKey);
}
}
Simple enough. However, when I run my file it gives me NoClassDefFoundError error:
Exception in thread "main" java.lang.NoClassDefFoundError:
com/amazonaws/services/kms/AWSKMSClientBuilder
at KmsExample.main(KmsExample.java:13)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
Caused by: java.lang.ClassNotFoundException:
com.amazonaws.services.kms.AWSKMSClientBuilder
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 6 more
In IntelliJ, I see my files have been imported fine, and all the JARS are there:
Ctrl/Cmd + B to jump to file declaration works fine, proving that the file is there.
So why am I still getting a NoClassDefFoundError?

You are missing the dependency that contains AWSKMSClientBuilder class. Just add the following to your build.gradle:
compile group: 'com.amazonaws', name: 'aws-java-sdk-kms', version: '1.11.171'

Related

Gradle does not import added dependency after build operation

I am using spring-boot version 1.5.12 and gradle 5.2.1.
I have added Sentry library in my project as mentioned in its documents like below :
implementation 'io.sentry:sentry:1.7.23'
Gradle downloads the related jarFile in : \.gradle\caches\modules-2\files-2.1\io.sentry\sentry\1.7.23
and also I can see it in my IDE in External Libraries part
then I configed it in my local environment and everything worked fine and I could see my Exception reports in Sentry dashboard.
but after that when I wanted to create a version of project for my production environment, the build operation ended successfully but this new library is not in the folder(which is the result of my build operation named Distribution) which contains myPro.jar and other libraries that I use , I faced the Exception :
Exception in thread "main" java.lang.NoClassDefFoundError: io/sentry/Sentry
at ir.anarestan.ipc.boot.Boot.initSentry(Boot.java:22)
at ir.anarestan.ipc.boot.Boot.main(Boot.java:17)
Caused by: java.lang.ClassNotFoundException: io.sentry.Sentry
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 2 more
here is my build.gradle file :
group 'pc-server'
version '0.2.1-SNAPSHOT'
apply plugin: 'java'
apply plugin: 'groovy'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
<some other dependecies>
implementation 'io.sentry:sentry:1.7.23'
}
apply plugin: 'application'
mainClassName = 'ir.anarestan.ipc.boot.Boot'
jar {
manifest {
attributes 'Main-Class': mainClassName,
'Class-Path': configurations.runtime.files.collect {"$it.name"}.join(' ')
}
}
task fatJar(type: Jar) {
manifest {
attributes 'Implementation-Title': 'Gradle Jar File PC',
'Implementation-Version': version,
'Main-Class': 'ir.anarestan.ipc.boot.Boot'
}
baseName = project.name + '-all'
from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } }
with jar
}
ext.distributionDir= "${rootDir}/dist/core"
ext.mainClassName = 'ir.anarestan.ipc.boot.Boot'
jar {
manifest {
attributes("Implementation-Title": project.name,
"Implementation-Version": version,
"Main-Class": mainClassName,
"Class-Path": configurations.compile.collect { it.getName() }.join(' '))
}
destinationDir = file("$distributionDir")
}
task copyLibs(type: Copy){
from configurations.compile
into "$distributionDir"
}
task copyConfig(type: Copy){
from "$projectDir/src/main/resources/"
into "$distributionDir"
}
task distribution(dependsOn: ['copyLibs', 'copyConfig', 'jar']){
}
and I face Exception here :
#SpringBootApplication
#EnableMongoRepositories(basePackages = {"ir.anarestan.ipc.repository.mongodb"})
public class Boot {
public static void main(String[] args) {
SpringApplication.run(Boot.class, args);
Sentry.init();
}
}
any help would be appreciated, it has take me lots of time!!!

How to use Kotlin with H2 and SQLite in Intellij

When I try to use Kotlin in Intellij with either SQLite or H2, Intellij gives me this error:
Exception in thread "main" java.lang.ClassNotFoundException: org.h2.Driver
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:264)
at org.jetbrains.exposed.sql.Database$Companion.connect(Database.kt:91)
at org.jetbrains.exposed.sql.Database$Companion.connect$default(Database.kt:90)
at MainKt.main(main.kt:9)
This is my Gradle file:
buildscript {
ext.kotlin_version = '1.2.20'
repositories {
mavenCentral()
}
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath "org.h2.Driver"
}
}
group '1'
version '1.0-SNAPSHOT'
apply plugin: 'kotlin'
repositories {
mavenCentral()
maven {
url "https://dl.bintray.com/kotlin/exposed"
}
}
dependencies {
compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
compile 'org.jetbrains.exposed:exposed:0.9.1'
}
compileKotlin {
kotlinOptions.jvmTarget = "1.8"
}
compileTestKotlin {
kotlinOptions.jvmTarget = "1.8"
}
This is my Kotlin file, where I try to use Exposed to interface with H2e some data persistence with Kotlin:
import org.jetbrains.exposed.sql.StdOutSqlLogger
import org.jetbrains.exposed.sql.Database
import org.jetbrains.exposed.sql.Table
import org.jetbrains.exposed.sql.insert
import org.jetbrains.exposed.sql.transactions.transaction
import org.jetbrains.exposed.sql.selectAll
fun main(args: Array<String>) {
Database.connect("jdbc:h2:mem:test", driver = "org.h2.Driver")
transaction {
logger.addLogger(StdOutSqlLogger)
val stPeteId = Cities.insert {
it[name] = "St. Petersburg"
} get Cities.id
println("Cities: ${Cities.selectAll()}")
}
}
object Cities : Table() {
val id = integer("id").autoIncrement().primaryKey()
val name = varchar("name", 50)
}
data class City(val id: Int, val name: String)
How do I use Kotlin with a database? This is not for Android; just a personal project in Intellij that I want to use eventually on a PC.
You actually need the h2 driver, wether you're in java or kotlin.
Add the com.h2database:h2 dependency to your gradle file and add the maven central if needed.
By the way, there's nothing wrong with your kotlin code. This would also not work if called from java like this, since you're missing the dependencies.

How to gradle matrix-toolkits-java (MTJ) without error?

I would like to use the MTJ library. But why do I get a ClassNotFoundException? How can I implement my build and code the right way?
First the error message, then the code example:
Error (gradle build; java -jar build/libs/tmp.jar):
Exception in thread "main" java.lang.NoClassDefFoundError: no/uib /cipr/matrix/DenseMatrix
at de.piphi.Main.readMatrix(Main.java:7)
at de.piphi.Main.main(Main.java:12)
Caused by: java.lang.ClassNotFoundException: no.uib.cipr.matrix.DenseMatrix
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
gradle.build:
apply plugin: 'java'
repositories{
jcenter()
mavenCentral()
}
dependencies {
compile group: 'com.googlecode.matrix-toolkits-java', name: 'mtj', version: '1.0.2'
}
jar {
manifest {
attributes 'Main-Class': 'de.piphi.Main'
}
}
src/main/java/de/piphi/Main.cpp:
package de.piphi;
import no.uib.cipr.matrix.*;
public class Main {
static void readMatrix(){
Matrix m = new DenseMatrix(2,2);
System.out.println(m);
}
public static void main(String[] args) {
readMatrix();
}
}
I know Is there any example how to use Matrix Toolkit Java (MTJ)?, but the wiki page mentioned does not exist anymore.
I had to add the plugin applications to build.gradle. In Main.cpp the import of import no.uib.cipr.matrix.*; must be
import no.uib.cipr.matrix.DenseMatrix;
I changed 'Matrix m = new DenseMatrix(2,2);' to
DenseMatrix m = new DenseMatrix(2,2);

Gradle NoClassDefFoundError when running jar

I'm trying to set up a Gradle project with some Velocity functions in it.
So far I have the following files:
src/main/java/com/veltes/velotest.java:
package com.veltes;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.exception.MethodInvocationException;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;
import java.io.*;
public class velotest {
public static void main(String[] args) {
try {
VelocityEngine ve = new VelocityEngine();
ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
ve.init();
VelocityContext context = new VelocityContext();
context.put("name", "World");
Template t = ve.getTemplate("com/veltes/velotest.vm");
StringWriter writer = new StringWriter();
t.merge(context, writer);
System.out.println(writer.toString());
File logFile = new File("C:/users/xxxx/Desktop/velotest.html");
try {
writeFile(logFile, t, context);
}
catch (IOException io) {
}
} catch (Exception e) {
}
}
private static void writeFile(File logFile, Template t, VelocityContext context) throws IOException {
Writer logWriter;
logWriter = new BufferedWriter(new FileWriter(logFile));
try {
t.merge(context, logWriter);
}
catch (ResourceNotFoundException rnfe) {
}
catch (ParseErrorException pee) {
}
catch (MethodInvocationException mie) {
}
catch (Exception e) {
}
logWriter.flush();
logWriter.close();
}
}
build.gradle:
group 'velocitytest'
version '1.0-SNAPSHOT'
apply plugin: 'groovy'
apply plugin: 'java'
sourceCompatibility = 1.5
repositories {
mavenCentral()
mavenLocal()
}
dependencies {
compile 'org.codehaus.groovy:groovy-all:2.3.11'
testCompile group: 'junit', name: 'junit', version: '4.11'
compile 'velocity:velocity:1.4'
}
Now, when I run gradle assemble and gradle build everything is fine, but when I try to run the project (same for running the built jar in build/libs/ and for running the velotest class in IntelliJ), I get the following error:
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/collections/ExtendedProperties
at org.apache.velocity.runtime.RuntimeInstance.< init >(RuntimeInstance.java:183)
at org.apache.velocity.app.VelocityEngine.(VelocityEngine.java:60)
at com.veltes.velotest.main(velotest.java:23)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
Caused by: java.lang.ClassNotFoundException: org.apache.commons.collections.ExtendedProperties
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 8 more
It's a bit strange that there is no jar in build/tmp/
Does anyone of you knows a solution?
You need to create a runnable jar if you want to be able to run it.
You can use shadojar plugin or extend the jar task to pack the runtime deps into an artifact.
jar {
archiveName = 'Name.jar'
manifest {
attributes 'Main-Class': 'your.main.class',
'Class-Path': configurations.runtime.files.collect { "lib/$it.name" }.join(' '),
'Implementation-Version': project.version
}
from(configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }) {}
}
For intelliJ problem:
apply plugin: 'idea'
Then run gradle idea task, this will refresh .iws .ipr .iml files in your project and sync the classpaths. Or if you use intelliJ support (which is not yet ideal) try to refresh it there. I think in version 2017.1.3 the gradle integration is a bit better.
Adding
from(configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }) {} to build.gradle file fixed it for me, like this:
jar {
manifest {
attributes(
'Main-Class': 'gradle22.Library'
)
}
from {
configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }
}
}

Couldn't build using gradle

I'm newer using Gradle, I have this file build.gradle:
apply plugin: 'maven'
apply plugin: 'spring-boot'
group = "com.test.sample"
sourceCompatibility = 1.8
targetCompatibility = 1.8
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:$springBootVersion")
classpath 'io.spring.gradle:dependency-management-plugin:0.6.1.RELEASE'
}
}
task wrapper(type: Wrapper) {
gradleVersion = '2.0'
}
repositories {
maven {
credentials {
username = nexusUsername
password = nexusPassword
}
url "${nexusUrl}/content/repositories/releases/ex--common/"
mavenCentral()
jcenter()
eventuateMavenRepoUrl.split(',').each { repoUrl -> maven { url repoUrl } }
}
}
dependencies {
compile "com.test.sample:EX--Common:${exCommonVersion}"
compile "com.test.sample:EX--CommonSwagger:${exCommonSwaggerVersion}"
compile("org.springframework.boot:spring-boot-devtools")
compile "org.springframework.boot:spring-boot-starter-web:$springBootVersion"
compile "org.springframework.boot:spring-boot-starter-actuator:$springBootVersion"
compile "io.eventuate.local.java:eventuate-local-java-jdbc:${eventuateLocalVersion}"
compile "io.eventuate.local.java:eventuate-local-java-embedded-cdc-autoconfigure:${eventuateLocalVersion}"
testCompile "junit:junit:4.11"
testCompile "org.springframework.boot:spring-boot-starter-test:$springBootVersion"
testCompile "io.eventuate.client.java:eventuate-client-java-jdbc:$eventuateClientVersion"
}
I install gradle 3.4.1 in my machine. When I do
gradle build
or
gradle assemble
I get this error:
Failed to apply plugin [class 'io.spring.gradle.dependencymanagement.DependencyManagementPlugin']
Could not create task of type 'DependencyManagementReportTask'.
Would you have any ideas how I can fix that?
This is the stacktrace info:
* Exception is:
org.gradle.api.GradleScriptException: A problem occurred evaluating project ':xxx'.
at org.gradle.groovy.scripts.internal.DefaultScriptRunnerFactory$ScriptRunnerImpl.run(DefaultScriptRunnerFactory.java:92)
at org.gradle.configuration.DefaultScriptPluginFactory$ScriptPluginImpl$2.run(DefaultScriptPluginFactory.java:176)
at org.gradle.configuration.ProjectScriptTarget.addConfiguration(ProjectScriptTarget.java:77)
at org.gradle.configuration.DefaultScriptPluginFactory$ScriptPluginImpl.apply(DefaultScriptPluginFactory.java:181)
.....
at org.gradle.internal.concurrent.StoppableExecutorImpl$1.run(StoppableExecutorImpl.java:46)
Caused by: org.gradle.api.internal.plugins.PluginApplicationException: Failed to apply plugin [id 'io.spring.dependency-management']
at org.gradle.api.internal.plugins.DefaultPluginManager.doApply(DefaultPluginManager.java:155)
at org.gradle.api.internal.plugins.DefaultPluginManager.apply(DefaultPluginManager.java:112)
at org.gradle.api.internal.plugins.DefaultObjectConfigurationAction.applyType(DefaultObjectConfigurationAction.java:113)
at org.gradle.api.internal.plugins.DefaultObjectConfigurationAction.access$200(DefaultObjectConfigurationAction.java:36)
at org.gradle.api.internal.plugins.DefaultObjectConfigurationAction$3.run(DefaultObjectConfigurationAction.java:80)
at org.gradle.api.internal.plugins.DefaultObjectConfigurationAction.execute(DefaultObjectConfigurationAction.java:136)
at org.gradle.api.internal.project.AbstractPluginAware.apply(AbstractPluginAware.java:44)
at org.gradle.api.internal.project.ProjectScript.apply(ProjectScript.java:34)
at org.gradle.api.Script$apply$0.callCurrent(Unknown Source)
at build_cq297at3shymhbbwfq82eq5ag.run(C:\Users\xxx\build.gradle:13)
at org.gradle.groovy.scripts.internal.DefaultScriptRunnerFactory$ScriptRunnerImpl.run(DefaultScriptRunnerFactory.java:90)
... 62 more
Caused by: org.gradle.api.tasks.TaskInstantiationException: Could not create task of type 'DependencyManagementReportTask'.
at org.gradle.api.internal.project.taskfactory.TaskFactory$1.call(TaskFactory.java:123)
at org.gradle.api.internal.project.taskfactory.TaskFactory$1.call(TaskFactory.java:118)
at org.gradle.util.GUtil.uncheckedCall(GUtil.java:402)
at org.gradle.api.internal.AbstractTask.injectIntoNewInstance(AbstractTask.java:178)
at org.gradle.api.internal.project.taskfactory.TaskFactory.create(TaskFactory.java:118)
at org.gradle.api.internal.project.taskfactory.TaskFactory.createTask(TaskFactory.java:77)
at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory.createTask(AnnotationProcessingTaskFactory.java:46)
at org.gradle.api.internal.project.taskfactory.DependencyAutoWireTaskFactory.createTask(DependencyAutoWireTaskFactory.java:39)
at org.gradle.api.internal.tasks.DefaultTaskContainer.create(DefaultTaskContainer.java:76)
at org.gradle.api.internal.tasks.DefaultTaskContainer.create(DefaultTaskContainer.java:111)
at org.gradle.api.internal.tasks.DefaultTaskContainer.create(DefaultTaskContainer.java:141)
at org.gradle.api.internal.tasks.DefaultTaskContainer_Decorated.create(Unknown Source)
at org.gradle.api.internal.tasks.DefaultTaskContainer_Decorated$create.call(Unknown Source)
at io.spring.gradle.dependencymanagement.DependencyManagementPlugin.apply(DependencyManagementPlugin.groovy:64)
at io.spring.gradle.dependencymanagement.DependencyManagementPlugin.apply(DependencyManagementPlugin.groovy)
at org.gradle.api.internal.plugins.ImperativeOnlyPluginApplicator.applyImperative(ImperativeOnlyPluginApplicator.java:35)
at org.gradle.api.internal.plugins.RuleBasedPluginApplicator.applyImperative(RuleBasedPluginApplicator.java:43)
at org.gradle.api.internal.plugins.DefaultPluginManager.doApply(DefaultPluginManager.java:139)
... 72 more
Caused by: org.gradle.internal.service.UnknownServiceException: No service of type StyledTextOutputFactory available in ProjectScopeServices.
at org.gradle.internal.service.DefaultServiceRegistry.getServiceProvider(DefaultServiceRegistry.java:436)
at org.gradle.internal.service.DefaultServiceRegistry.doGet(DefaultServiceRegistry.java:426)
at org.gradle.internal.service.DefaultServiceRegistry.get(DefaultServiceRegistry.java:414)
at org.gradle.api.internal.DependencyInjectingInstantiator.convertParameters(DependencyInjectingInstantiator.java:81)
at org.gradle.api.internal.DependencyInjectingInstantiator.newInstance(DependencyInjectingInstantiator.java:54)
at org.gradle.api.internal.ClassGeneratorBackedInstantiator.newInstance(ClassGeneratorBackedInstantiator.java:36)
at org.gradle.api.internal.project.taskfactory.TaskFactory$1.call(TaskFactory.java:121)
... 89 more
Best regards

Categories

Resources