How to fix "java.lang.NoClassDefFoundError: com/microsoft/azure/eventhubs/EventHubClient$" error in Java - azure-eventhub

Java Version: 1.8
Azure EventHubs Version: 3.0.1
I'm trying to connect to my EventHubClient by calling:
EventHubClient.createFromConnectionStringSync(connStr.toString(), executorService)
However, this call is throwing a NoClassDefFoundError of the following:
java.lang.NoClassDefFoundError: com/microsoft/azure/eventhubs/EventHubClient$
Usually when I run into a NoClassDefFoundError, it is because I didn't import the corresponding package. However, in this case, I have the Azure EventHub package imported. The thing that is confusing me the most is the '$' at the end of EventHubClient.
Has anyone ran into this issue before and know what may be causing it?

Firstly, i suppose that the official code is totally right and nothing wrong with your jdk version and event hub package version because i tested the sample code with your environment and it works for me.
dependencies:
Sample code:
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.microsoft.azure.eventhubs.ConnectionStringBuilder;
import com.microsoft.azure.eventhubs.EventData;
import com.microsoft.azure.eventhubs.EventHubClient;
import com.microsoft.azure.eventhubs.EventHubException;
import java.io.IOException;
import java.nio.charset.Charset;
import java.time.Instant;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
public class SimpleSend {
public static void main(String[] args)
throws EventHubException, ExecutionException, InterruptedException, IOException {
final ConnectionStringBuilder connStr = new ConnectionStringBuilder()
.setNamespaceName("jaygongeventhub")
.setEventHubName("jaygong")
.setSasKeyName("RootManageSharedAccessKey")
.setSasKey("4RXaJ2NPwz635HYlOpKGMCh89N/9i1kz3PSAC9WeYq0=");
final Gson gson = new GsonBuilder().create();
final ScheduledExecutorService executorService = Executors.newScheduledThreadPool(4);
final EventHubClient ehClient = EventHubClient.createFromConnectionStringSync(connStr.toString(), executorService);
try {
for (int i = 0; i < 10; i++) {
String payload = "Message " + Integer.toString(i);
byte[] payloadBytes = gson.toJson(payload).getBytes(Charset.defaultCharset());
EventData sendEvent = EventData.create(payloadBytes);
ehClient.sendSync(sendEvent);
}
System.out.println(Instant.now() + ": Send Complete...");
System.out.println("Press Enter to stop.");
System.in.read();
} finally {
ehClient.closeSync();
executorService.shutdown();
}
}
}
Output:
Secondly, based on your error detail: NoClassDefFoundError,which is different with ClassNotFoundException. ClassNotFoundException comes when JVM tries to the load a class at runtime dynamically means you give the name of the class at runtime and then JVM tries to load it and if that class is not found in the classpath it throws java.lang.ClassNotFoundException. While in the case of NoClassDefFoundError the problematic class was present during Compile time and that's why the program successfully compiled but not available during runtime for any reason.
I suggest you checking below solutions or points to try to solving the issue:
1) The class is not available in Java Classpath.
2) You might be running your program using jar command and class was not defined in manifest file's ClassPath attribute.
3) Any start-up script is overriding Classpath environment variable.
4) Because NoClassDefFoundError is a subclass of java.lang.LinkageError it can also come if one of it dependency like native library may not available.
4) Check for java.lang.ExceptionInInitializerError in your log file. NoClassDefFoundError due to the failure of static initialization is quite common.
5) If you are working in J2EE environment than the visibility of Class among multiple Classloader can also cause java.lang.NoClassDefFoundError, see examples and scenario section for detailed discussion.
Read more: https://javarevisited.blogspot.com/2011/06/noclassdeffounderror-exception-in.html#ixzz62y4liZ3G
Read more: https://javarevisited.blogspot.com/2011/06/noclassdeffounderror-exception-in.html#ixzz62y4NPiEB

Related

Android Studio Error : Cannot resolve symbol CreateTodoInput and CreateTodoMutation

I am trying to build an Android app using AWS Amplify CLI.
I am following the AWS documentation. However, I am getting this error, in Android Studio:
Cannot resolve symbol CreateTodoInput and CreateTodoMutation
I have pasted all the dependencies as present in the documentation in my app and project Gradle files.
I found a similar question (Can not resolve symbol CreateTodoInput), but the answer provided doesn't resolve my issue.
My entire code is in MainActivity.java:
package com.example.testamplify;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import com.amazonaws.mobile.config.AWSConfiguration;
import com.amazonaws.mobileconnectors.appsync.AWSAppSyncClient;
import com.apollographql.apollo.GraphQLCall;
import com.apollographql.apollo.exception.ApolloException;
import javax.annotation.Nonnull;
public class MainActivity extends AppCompatActivity {
private AWSAppSyncClient mAWSAppSyncClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAWSAppSyncClient = AWSAppSyncClient.builder()
.context(getApplicationContext())
.awsConfiguration(new AWSConfiguration(getApplicationContext()))
.build();
runMutation();
}
public void runMutation() {
CreateTodoInput createTodoInput = CreateTodoInput.builder()
.name("Use AppSync")
.description("Realtime and Offline")
.build();
mAWSAppSyncClient
.mutate(CreateTodoMutation.builder()
.input(createTodoInput).build()
)
.enqueue(mutationCallback);
}
private GraphQLCall.Callback<CreateTodoMutation.Data> mutationCallback =
new GraphQLCall.Callback<CreateTodoMutation.Data>() {
#Override
public void onResponse(#Nonnull Response<CreateTodoMutation.Data> response) {
Log.i("Results", "Added Todo");
}
#Override
public void onFailure(#Nonnull ApolloException e) {
Log.e("Error", e.toString());
}
};
}
Syncing my project with gradle files resolved the issue !!
I had the same problem as I'm new and experimenting with this too. I think CreateTodo is a type of variable. Download this example of an android app provided by AWS, found here. Open the ListEventsActivity, on line 77. You will see this same code, hope it helps you understand, it helped me.
Retry the tutorial again, and when you use amplify add api, after amplify push.
It'll ask the follow Do you want to generate code for your newly created GraphQL API. At first i choose no, and the folder graphql was not generated.
So, when the prompt ask
Do you want to generate code for your newly created GraphQL API
You have to answer yes and configure with the default values.
At least, that was wrong wit me, give it a try.

embedded jetty ignoring classes packaged in my war

I'm trying to run jetty in embedded mode. It appears to be ignoring all the classes bundled in my war file, whether under WFB-INF/classes or WEB-INF/lib.
My startup code:
package rfd;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.util.resource.Resource;
import org.eclipse.jetty.webapp.WebAppContext;
import org.eclipse.jetty.xml.XmlConfiguration;
public class RfdWar
{
public static void main(String[] args) throws Exception
{
System.setProperty("org.eclipse.jetty.LEVEL", "DEBUG");
Server server = new Server(8080);
org.eclipse.jetty.webapp.Configuration.ClassList classlist = org.eclipse.jetty.webapp.Configuration.ClassList.setServerDefault(server);
classlist.addAfter("org.eclipse.jetty.webapp.FragmentConfiguration", "org.eclipse.jetty.plus.webapp.EnvConfiguration", "org.eclipse.jetty.plus.webapp.PlusConfiguration");
Resource jettyEnv = Resource.newSystemResource("jetty-env.xml");
XmlConfiguration conf = new XmlConfiguration(jettyEnv.getInputStream());
Object obj = conf.configure();
WebAppContext context = (WebAppContext)obj;
context.setWar("/tmp/thewar.war");
context.setContextPath("/");
context.setParentLoaderPriority(true);
server.setHandler(context);
server.start();
server.join();
}
}
My command line:
export JETTYHOME=<my_jetty_home>
JHL=$JETTYHOME/lib
export CLASSPATH=.:$JHL/jetty-server-9.2.10.v20150310.jar:$JHL/jetty-util-9.2.10.v20150310.jar:$JHL/jetty-http-9.2.10.v20150310.jar:$JHL/servlet-api-3.1.jar:$JHL/jetty-io-9.2.10.v20150310.jar:$JHL/jetty-webapp-9.2.10.v20150310.jar:$JHL/jetty-servlet-9.2.10.v20150310.jar:$JHL/jetty-security-9.2.10.v20150310.jar:$JHL/jetty-xml-9.2.10.v20150310.jar:$JHL/jetty-plus-9.2.10.v20150310.jar:$JHL/jetty-jndi-9.2.10.v20150310.jar:$JHL/jsp/javax.servlet.jsp-2.3.2.jar:$JHL/jsp/javax.servlet.jsp-api-2.3.1.jar
java rfd.RfdWar
The server does launch correctly and definitely reads web.xml packaged in the war. But when I try accessing the URL I'm getting an error that my class, that's packaged with the war, is missing.
Is there anything else I need to do to tell jetty to honor the classes packaged in the war?
This command ...
context.setParentLoaderPriority(true);
Basically says that when the webapp is attempting to load a class, the server classpath is checked first, then the webapp's classpath.
So if you happen to have the same classes in both places, the server version will be used, ignoring the one on the webapp.
Set this to false to get honest servlet spec behavior, with all of the WebApp classloader isolation.
Also, this is wrong, in many different ways.
Resource jettyEnv = Resource.newSystemResource("jetty-env.xml");
XmlConfiguration conf = new XmlConfiguration(jettyEnv.getInputStream());
Object obj = conf.configure();
WebAppContext context = (WebAppContext)obj;
The proper way to get jetty-env.xml to be loaded is to use the establish the WebApp and ClassList Configuration that performs this function from within the appropriate classloader and thread scope.
See documentation at https://www.eclipse.org/jetty/documentation/current/jndi-embedded.html
And prior answer at Can't get jetty to read jetty-env.xml

Http.Context with FakeApplication and illusive mock method

In my tests I create a fake application per test method:
#Before
public void startFakeApplication() {
this.fakeApplication = fakeApplication();
start(this.fakeApplication);
}
#After
public void killFakeApplication() {
stop(this.fakeApplication);
this.fakeApplication = null;
}
Some of the tests use functionality that checks if the request is secure or not:
public boolean isHttps() {
Http.Request req = Controller.request();
return req.getHeader("x-forwarded-proto") != null
&& req.getHeader("x-forwarded-proto").contains("https");
}
That fails saying:
There is no HTTP Context available from here
Which is pretty strange, since it's running on a fake app, why can't it know that and create a fake request?
Oh well, I found this: Play framework 2.2.1: Create Http.Context for tests which introduced me to the mocking approach, so I was eager to give it a go and try to mock the Http.Context in the same way, the problem is that I can't seem to find the mock method...
In that thread he's using import static org.mockito.Mockito.* (which is where I assume the mock method is located) but I don't have that package, org.mockito only has one sub package named internal and I can't find any mock method there.
In the official documentation of Play! the only place talking about it is the Scala Test section and they use: import org.specs2.mock._ but there too I wasn't able to locate this mock method.
I'm using Play 2.2.2 (java).
Any ideas? Thanks.
I solved the same problem adding to my build.sbt the library dependency of Mockito:
libraryDependencies += "org.mockito" % "mockito-core" % "1.10.19"
Then I run play compile and play eclipse and magically the mockito library became available after refreshing the whole project in Eclipse.
And yes, mock() is a method of org.mockito.Mockito.
I had the same problem of Play not locating the mock function, and eventually realised that I hadn't extended my test class with Mockito;
import org.specs2.mock._
class TestClass extends Specification with Mockito
Just thought I'd add this as it has taken me ages to resolve and the above solution didn't work for me ......may save someone some time :)

JAVA JAX-WS NullPointerException at javax.xml.ws.Service.getPort(Service.java:188)

I have simple "HelloWorld" web service deployed on jboss under ubuntu.
I have created simple client, but I can't get it to work. I'm getting NullPointerException each time I run the client.
Note that I'm running on Oracle Java 7 under Ubuntu.
Here is the code:
HelloWorldClient.java
import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
public class HelloWorldClient {
public static void main(String[] args){
URL url;
try {
url = new URL("http://localhost:8080/WebServiceProject/helloWorld?wsdl");
QName qname = new QName("http:///", "HelloWorldImplService");
Service service = Service.create(url, qname);
HelloWorld hello = service.getPort(HelloWorld.class);
System.out.println(hello.sayHello("mkyong"));
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
HelloWorld.java
import javax.jws.WebMethod;
import javax.jws.WebService;
#WebService
public interface HelloWorld {
#WebMethod
public String sayHello(String name);
}
Stacktrace:
Exception in thread "main" java.lang.NullPointerException
at com.sun.xml.internal.ws.model.RuntimeModeler.getPortTypeName(RuntimeModeler.java:1407)
at com.sun.xml.internal.ws.client.WSServiceDelegate.getPort(WSServiceDelegate.java:334)
at com.sun.xml.internal.ws.client.WSServiceDelegate.getPort(WSServiceDelegate.java:354)
at javax.xml.ws.Service.getPort(Service.java:188)
at HelloWorldClient.main(HelloWorldClient.java:18)
The exception is thrown at this line:
HelloWorld hello = service.getPort(HelloWorld.class);
I have had the same problem myself for a few days now, because the WSDL-file (and service) I was using was moved to a new URL. I finally found the solution here:
http://techtracer.com/2007/08/15/jax-ws-jaxp-tutorial-building-a-stockquote-web-service-client/
In short, everything (should have) started working after I re-generated all the auto-generated java and class files with the following command (on Windows/CygWin)
"C:/Program Files/Java/jdk1.8.0_31/bin/wsimport.exe" -keep https://domain.com/path_to_wsdl
I had some extra trouble because some old files were left around and clashing with the newly generated ones, but everything slowly started working after I moved all the old files to the recycle bin.
It can also happen if your web-service's implementation is different than the interface from your project.
If in your project you have HelloWorld.class declaring some methods that are not present on the web-service side, the getPort(HelloWorld.class) call will raise a null pointer exception.
You can double check the HelloWorld.class interface on your application and the one on the web-service itself to make sure they match.

how to resolve "java.lang.NoClassDefFoundError: org/apache/velocity/context/Context"

I'm a new learner of apache cxf. in the first program i implement, i encoutered the following exception( this is what my console display):
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/velocity/context/Context
The java code source i run is
package com.ttdev;
import org.apache.cxf.tools.wsdlto.WSDLToJava;
public class CodeGenerator {
/**
* #param args
*/
public static void main(String[] args) {
System.out.println("debug");
WSDLToJava.main(new String[] {
"-server",
"-d", "src/main/java",
"src/main/resources/Service.wsdl" });
System.out.println("Done!");
}
}
so how can i resolve this problem.
You need Apache Velocity on your classpath.
Check your Pom->DependencyHierarchy -> Filter "velocity"
In which package it is found , Probably it was not loaded properly.
In mycase it was C:\Users\MyUser.m2\repository\org\apache\velocity
Delete that and run "mvn clean package -DskipTests" from console, it will download all necessary packages.