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

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.

Related

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

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

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: ServletContextListener that registers a ServletRequestListener

I am using embedded Jetty v9.4.x and have the following issue:
My server registers a ServletContextListener:
final WebAppContext context = new WebAppContext();
// add listener
context.addLifeCycleListener(new AbstractLifeCycle.AbstractLifeCycleListener() {
#Override
public void lifeCycleStarting(LifeCycle event) {
ContextHandler.Context ctx = context.getServletContext();
ctx.setExtendedListenerTypes(true);
ctx.addListener("LISTENER_CLASS_NAME");
}
});
My listener gets called on Servet start. However, my context listener registers a ServletRequestListener inside:
servletContext.addListener(foo.MyServletRequestListener.class);
And this fails with the following exception:
java.lang.UnsupportedOperationException
at org.eclipse.jetty.servlet.ServletContextHandler$Context.addListener(ServletContextHandler.java:1506)
And when I looked it seems that context is not enabled (at least, this flags makes an exception to be thrown).
When I run the same application with the web.xml everything works.
How can I let the contextListener register a ServletRequestListener?
edit
There is explict note in Jetty code:
//toggle state of the dynamic API so that the listener cannot use it
This is enabled only on programatically added listeners - using API and not web-xml.
How I can make this work???
There are many different kinds of listeners in Jetty, each with their own specific set of add/remove/get/set methods.
Your AbstractLifeCycleListener is a Jetty LifeCycle listener, applying specifically for the Jetty internal starting/started/stopping/stopped of the various beans within Jetty.
Your implementation of this listener in your question is incomplete and shows a lack of understanding of the LifeCycleEvent (you are not looking for a specific bean to be started), your implementation will run hundreds of times. (once for each bean being started).
The use of ServletContext.addListener() has rules around it, and those specify that it can only be used during the ServletContext initialization phase (not before, not after). The use of ServletContext.addListener() outside of this phase is supposed to throw an IllegalStateException (the javadoc even says so)
The ServletContext.addListener() also has a limited set of servlet Listeners that are allowed to be used with it, far less then the number of listeners types that are valid with a Web App, or can be declared within a WEB-INF/web.xml, or flagged with the #WebListener annotation.
The only way to use the ServletContext.addListener() is from within the webapp itself, using webapp code, from within the webapp's own classloader.
The places to use ServletContext.addListener() are ...
ServletContainerInitializer.onStartup()
ServletContextListener.contextInitialized()
Filter.init()
Servlet.init()
As you can see, all of these locations are defined from within the webapp itself.
The existence of ServletContextHandler.addEventListener(EventListener) is an embedded-jetty work around, which allows the Listener to be added on construction of the ServletContextHandler, but not called until the actual event occurs.
The use of ServletContextHandler.addEventListener(EventListener) is equivalent to using the WEB-INF/web.xml to declare the Listener you are interested in having be used.
Example:
package jetty.listener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.DefaultHandler;
import org.eclipse.jetty.server.handler.HandlerList;
import org.eclipse.jetty.servlet.DefaultServlet;
import org.eclipse.jetty.servlet.ServletContextHandler;
public class ServletContextListenerExample
{
public static void main(String[] args) throws Exception
{
Server server = new Server(8080);
ServletContextHandler context = new ServletContextHandler();
context.setContextPath("/");
MyContextListener contextListener = new MyContextListener();
context.addEventListener(contextListener);
// for context based static file serving and error handling
context.addServlet(DefaultServlet.class, "/");
HandlerList handlers = new HandlerList();
handlers.addHandler(context);
// for non-context error handling
handlers.addHandler(new DefaultHandler());
server.setHandler(handlers);
server.start();
server.join();
}
public static class MyContextListener implements ServletContextListener
{
#Override
public void contextInitialized(ServletContextEvent sce)
{
System.err.printf("MyContextListener.contextInitialized(%s)%n", sce);
sce.getServletContext().addListener(new MyRequestListener());
}
#Override
public void contextDestroyed(ServletContextEvent sce)
{
System.err.printf("MyContextListener.contextDestroyed(%s)%n", sce);
}
}
public static class MyRequestListener implements ServletRequestListener
{
#Override
public void requestDestroyed(ServletRequestEvent sre)
{
System.err.printf("MyRequestListener.requestDestroyed(%s)%n", sre);
}
#Override
public void requestInitialized(ServletRequestEvent sre)
{
System.err.printf("MyRequestListener.requestInitialized(%s)%n", sre);
}
}
}
This will register MyContextListener which implements both javax.servlet.ServletContextListener.
When the ServletContext initialization phase kicks in, the contextInitialized() event is triggered.
The implementation of contextInitalized() then uses the passed in ServletContext to add a new MyRequestListener (which implements javax.servlet.ServletRequestListener) via the ServletContext.addListener() API.
Output of the above, and hitting http://localhost:8080/ from a browser ...
2018-06-28 09:42:06.352:INFO::main: Logging initialized #340ms to org.eclipse.jetty.util.log.StdErrLog
2018-06-28 09:42:06.475:INFO:oejs.Server:main: jetty-9.4.11.v20180605; built: 2018-06-05T18:24:03.829Z; git: d5fc0523cfa96bfebfbda19606cad384d772f04c; jvm 9.0.4+11
MyContextListener.contextInitialized(javax.servlet.ServletContextEvent[source=ServletContext#o.e.j.s.ServletContextHandler#12e61fe6{/,null,STARTING}])
2018-06-28 09:42:06.532:INFO:oejsh.ContextHandler:main: Started o.e.j.s.ServletContextHandler#12e61fe6{/,null,AVAILABLE}
2018-06-28 09:42:06.695:INFO:oejs.AbstractConnector:main: Started ServerConnector#4567f35d{HTTP/1.1,[http/1.1]}{0.0.0.0:8080}
2018-06-28 09:42:06.695:INFO:oejs.Server:main: Started #690ms
MyRequestListener.requestInitialized(javax.servlet.ServletRequestEvent[source=ServletContext#o.e.j.s.ServletContextHandler#12e61fe6{/,null,AVAILABLE}])
MyRequestListener.requestDestroyed(javax.servlet.ServletRequestEvent[source=ServletContext#o.e.j.s.ServletContextHandler#12e61fe6{/,null,AVAILABLE}])
Caution: Be aware that there are many more listener APIs and listener types on Jetty then discussed here, they exist for other features / components with Jetty that are unrelated to your question.
Don't get hung up on them, skip them, ignore them and you'll be fine.

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

Runtime exception with jersey - java.lang.AbstractMethodError

I am trying to execute a RESTful web service deployed on tomcat using Jersey implementation.
Following is the resource class
#Path("/rest")
public class PatientResource {
PatientService patientService;
#GET
#Path("/patient/{patientId}")
#Produces(MediaType.APPLICATION_JSON)
public Patient getPatientDetails(#PathParam("patientId") String patientId) {
//return patientService.getPatientDetails(patientId);
return new PatientService().getPatientDetails(patientId);
}
#GET
#Path("/patients")
#Produces(MediaType.APPLICATION_JSON)
public PatientData<Patient> getAllPatients() {
//return patientService.getAllPatients();
return new PatientService().getAllPatients();
}
}
I have made necessary entries in web.xml and all necessary jars are available in classpath, however when application is started on tomcat and I enter the URL in browser, I get following exception
[Servlet execution threw an exception] with root cause
java.lang.AbstractMethodError
at org.codehaus.jackson.map.AnnotationIntrospector$Pair.findSerializer(AnnotationIntrospector.java:1148)
at org.codehaus.jackson.map.ser.BasicSerializerFactory.findSerializerFromAnnotation(BasicSerializerFactory.java:367)
at org.codehaus.jackson.map.ser.BeanSerializerFactory.createSerializer(BeanSerializerFactory.java:252)
at org.codehaus.jackson.map.ser.StdSerializerProvider._createUntypedSerializer(StdSerializerProvider.java:782)
Any idea how to resolve it ?
Probably an inconsistency in the versions of Jersey and Jackson you are using at runtime .
What are your libs versions ?