I have created a simple web service called TimeServerBean. It's working properly, the GlassFish server is running and I can access the WSDL file from browser. Note this is done on local host.
Next I created a new project and made a web service client and provided the URL to the WSDL file. Then I got some classes generated (JAX-WS).
On my client class I have this code:
public class SimpleClient {
#WebServiceRef(wsdlLocation = "wsdl url here")
static TimeServerBean_Service service;
private TimeServerBean bean;
public SimpleClient() {
bean = service.getTimeServerBeanPort();
}
//methods here
}
Although I get null when I call the getTimeServerBeanPort. During that time the server is up and running. Is there some obvious mistake? TimeServerBean and TimeServerBean_Service are generated classes from the WSDL.
Two suggestions:
DEFINITELY put your method in a try/catch block
Assuming that service itself is null, then try doing an explicit service.create() instead of using the #WebServiceRef annotation. Here's a good example (Websphere, but same principle):
http://www-01.ibm.com/support/docview.wss?uid=swg21264135
The #WebServiceRef annotation is only supported in certain class types. Examples are JAX-WS endpoint implementation classes, JAX-WS handler classes, Enterprise JavaBeans classes, and servlet classes. This annotation is supported in the same class types as the #Resource annotation. See the Java Platform, Enterprise Edition (Java EE) 5 specification for a complete list of supported class types.
I generally do it by creating an instance using the interface and the class.
public class SimpleClient {
// interface TimeServerBean_Service class TimeServerBean
#WebServiceRef(wsdlLocation = "wsdl url here")
static TimeServerBean_Service port = new TimeServerBean.getTimeServerBeanPort();
public static void main(String[] args) {
try {
System.out.println(port);
System.out.println(port.methodWS("args"));
} catch (Exception e) {
e.printStackTrace();
}
}
//methods here
}
Related
I am new to web service programming and trying to create a JAX-WS web-service. I have created the following JAX-WS web service in Eclipse:
Creating the service interface:
package test;
#WebService
#SOAPBinding(style = Style.RPC)
public interface AdditionService {
#WebMethod
int add(int a,int b);
}
After that one implementation class:
package test;
#WebService(endpointInterface = "test.AdditionService")
public class AdditionServiceImpl implements AdditionService{
#Override
public int add(int a, int b) {
return a+b;
}
}
Last step:
By using the following code I am publishing the service:
package test;
public class AddtionServicePublisher {
public static void main(String[] args) {
Endpoint.publish
("http://localhost:9999/ws/additionService",
new AdditionServiceImpl());
}
}
I can view the wsdl using the bellow local URL:
http://localhost:9999/ws/additionService?wsdl
But as I don't have any server installed. How, it is getting published? Is server is inbuilt with eclipse?
The Oracle Java documentation states the following
Creates and publishes an endpoint for the specified implementor object at the given address.
The necessary server infrastructure will be created and configured by the JAX-WS implementation using some default configuration.
As JAX-WS is part of the Java SE package, this means the underlying server is depending on what kind of JVM you are running your program at. E.g. on my laptop I am running a Java 8 OpenJDK, in which an instance of "com.sun.net.httpserver.HttpServer" is created.
The fastest way to find out what server ist started in your environment, just jump into the (decompiled) code of the Endoint.java and the implementation(s).
If you want to create a standalone, selfrunning Webservice-jar you might be interested to take a look at Spring-WS (with Spring Boot) or Dropwizard.
I'm writing custom JAX-RS 2.0 application (under Jersey 2.3.1) which holds some data for use by all the resources.
public class WebApp extends org.glassfish.jersey.server.ResourceConfig {
public WebApp() {
packages("my.resources.package");
}
}
(I could use API's javax.ws.rs.core.Application as well, the described result is the same)
Then I inject the object into a resource
#Path("test")
public class Test {
#Context
Application app;
#GET
#Path("test")
public String test() {
return "Application class: " + app.getClass();
}
}
However, the result of a call is
Application class: class org.glassfish.jersey.server.ResourceConfig$WrappingResourceConfig
which makes me use some ugly tricks like
if (app instanceof WebApp) {
return (WebApp) app;
} else if (app instanceof ResourceConfig) {
return (WebApp) ((ResourceConfig) app).getApplication();
}
My understanding of JAX-RS 2.0 spec section 9.2.1:
The instance of the application-supplied Application subclass can be injected into a class field or method parameter using the #Context annotation. Access to the Application subclass instance allows configuration information to be centralized in that class. Note that this cannot be injected into the Application subclass itself since this would create a circular dependency.
is that application-supplied Application subclass is mine WebApp, not JAX-RS implementation-specific wrapper.
Also, changing this fragment
#Context
Application app;
to this
#Context
WebApp app;
causes app to be null, due to ClassCastException during context injection, so the declared type doesn't matter.
Is it a bug in Jersey or my misunderstanding?
UPDATE: I checked the behaviour under RESTEasy 3.0. The injected object is my WebApp, without any wrappers. I'd call it a bug in Jersey.
This doesn't seem like a bug. According to JAX-RS 2.0 spec you can inject Application into your resource classes (for example) but it does not say anything about directly injecting custom extensions of the Application. Not sure what your use-case is but you can register custom HK2 binder that will allow you to inject directly WebApp into resources:
public class WebApp extends org.glassfish.jersey.server.ResourceConfig {
public WebApp() {
packages("my.resources.package");
register(new org.glassfish.hk2.utilities.binding.AbstractBinder() {
#Override
protected void configure() {
bind(WebApp.this);
}
});
}
}
I too have encountered this using Jersey 2.4.1.
FWIW: I agree it seems like a bug according to the spec para 8.2.1. The statement "The instance of the application-supplied Application subclass" seems perfectly clear.
I have an alternative workaround that doesn't involve glassfish.hk2 but still concentrates the Jersey-specific code in the Application-derived class.
public class MyApp extends ResourceConfig {
...
static MyApp getInstance( Application application) {
try {
// for a conformant implementation
return (MyApp) application;
} catch (ClassCastException e) {
// Jersey 2.4.1 workaround
ResourceConfig rc = (ResourceConfig) application;
return (MyApp) rc.getApplication();
}
}
...
}
public class MyResource {
...
#Context Application application;
...
SomeMethod() {
... MyApp.getInstance( application);
}
}
Hope this is useful.
This appears to be fixed in a later version og Jersey. The same approach works for me with Jersey 2.16 at least. My injected Application object is of the correct subclass without any wrapping whatsoever.
Edit: Or maybe the version is irrelevant after all. Please see the comments to this answer.
I have a web service (JAX-RPC) that runs on application server (Websphere Application Server 7.0).
Normally the development process looks like this:
I write a class with web service implementation (e.g. MyService.java)
The IDE generates web service endpoint interface (e.g. MyService_SEI.java)
The IDE generates configuration XMLs
When the web service is deployed, MyService_SEI is the declared service interface and the application server instantiates a MyService instance by means of the public no-arg constructor.
But what if I want to do constructor injection (i.e. have MyService class without a no-arg constructor) or if I want to provide a dynamic proxy object which implements MyService_SEI and use that?
Is there a way I can take control of the instantiation procedure (like a filter or interceptor) to achieve this?
You can't do constructor injection as Injection always occur after the default constructor is called. If you try to use an injected reference inside the default constructor it will ALWAYS fail, there's no workaround for this as this is mandate by the specification.
So the first option you mentioned is discarded.
For the second option, using a filter or interceptor, you actually have an option. WebSphere WebServices are build using Axis2 implementation and Axis provide a way of implementing Handlers.
You can add handlers into the JAX-WS runtime environment to perform additional processing of request and response messages.
Here's a handler example, from Axis documentation:
package org.apache.samples.handlersample;
import java.util.Set;
import javax.xml.namespace.QName;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.handler.soap.SOAPMessageContext;
public class SampleProtocolHandler implements
javax.xml.ws.handler.soap.SOAPHandler<SOAPMessageContext> {
public void close(MessageContext messagecontext) {
}
public Set<QName> getHeaders() {
return null;
}
public boolean handleFault(SOAPMessageContext messagecontext) {
return true;
}
public boolean handleMessage(SOAPMessageContext messagecontext) {
Boolean outbound = (Boolean) messagecontext.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
if (outbound) {
// Include your steps for the outbound flow.
}
return true;
}
}
And than you add a handler.xml file like this:
<?xml version="1.0" encoding="UTF-8"?>
<jws:handler-chain name="MyHandlerChain">
<jws:protocol-bindings>##SOAP11_HTTP ##ANOTHER_BINDING</jws:protocol-bindings>
<jws:port-name-pattern
xmlns:ns1="http://handlersample.samples.apache.org/">ns1:MySampl*</jws:port-name-pattern>
<jws:service-name-pattern
xmlns:ns1="http://handlersample.samples.apache.org/">ns1:*</jws:service-name-pattern>
<jws:handler>
<jws:handler-class>org.apache.samples.handlersample.SampleLogicalHandler</jws:handler-class>
</jws:handler>
<jws:handler>
<jws:handler-class>org.apache.samples.handlersample.SampleProtocolHandler2</jws:handler-class>
</jws:handler>
<jws:handler>
<jws:handler-class>org.apache.samples.handlersample.SampleLogicalHandler</jws:handler-class>
</jws:handler>
<jws:handler>
<jws:handler-class>org.apache.samples.handlersample.SampleProtocolHandler2</jws:handler-class>
</jws:handler>
</jws:handler-chain>
an easy method would be to make two classes. one your class with all the bells and whistles (constructor injection etc lets call it worker). and the actual service. the service would delegate what it needs to the worker class, who it can get by calling some factory method.
The factory can even look at some common db or other config to decide which run time instance (which class, what config, shared or common) so you have good separation and power
Just cause you are using one framework/ method of injection does not mean you cannot mix to make it more powerful
In order to get GWT RequestFactory running with Grails, I am using the following approach:
class GwtController extends RequestFactoryServlet {
public GwtController() {
super()
}
def index = {
doPost request, response
}
#Override
public ServletContext getServletContext() {
return ServletContextHolder.servletContext
}
#Override
public ServletConfig getServletConfig() {
return new DummyServletConfig(getServletContext(),"grails");
}
}
where DummyServletConfig is a simple implementation of ServletConfig
This is working when deploying the app to tomcat. However, using testing or development mode, it is not. I was required to adjust the GWT Servlet in order to prevent it from using the wrong Class Loader:
In line 46 I changed
private static final RequestFactoryInterfaceValidator validator =
new RequestFactoryInterfaceValidator(log,
new RequestFactoryInterfaceValidator.ClassLoaderLoader(
ServiceLayer.class.getClassLoader()));
to
private static final RequestFactoryInterfaceValidator validator = new RequestFactoryInterfaceValidator(
log, new RequestFactoryInterfaceValidator.ClassLoaderLoader(
Thread.currentThread()
.getContextClassLoader()));
Otherwise, it wouldn't find my Domain classes (which apparently do not reside in the GrailsRootLoader but in the Thread's class loader).
Now I would like to revert my GWT servlet to the official binary released by Google and I wonder how I can fix the incorrect ClassLoader in Grails or make the RequestFactoryServlet work correctly without altering the GWT source.
I hope that GWT 2.3 will fix your problem:
http://code.google.com/p/google-web-toolkit/issues/detail?id=6092
I've added the following in my web.xml:
<ejb-ref>
<ejb-ref-name>ejb/userManagerBean</ejb-ref-name>
<ejb-ref-type>Session</ejb-ref-type>
<home>gha.ywk.name.entry.ejb.usermanager.UserManagerHome</home>
<remote>what should go here??</remote>
</ejb-ref>
The following java code is giving me NamingException:
public UserManager getUserManager () throws HUDException {
String ROLE_JNDI_NAME = "ejb/userManagerBean";
try {
Properties props = System.getProperties();
Context ctx = new InitialContext(props);
UserManagerHome userHome = (UserManagerHome) ctx.lookup(ROLE_JNDI_NAME);
UserManager userManager = userHome.create();
WASSSecurity user = userManager.getUserProfile("user101", null);
return userManager;
} catch (NamingException e) {
log.error("Error Occured while getting EJB UserManager" + e);
return null;
} catch (RemoteException ex) {
log.error("Error Occured while getting EJB UserManager" + ex);
return null;
} catch (CreateException ex) {
log.error("Error Occured while getting EJB UserManager" + ex);
return null;
}
}
The code is used inside the container. By that I mean that the .WAR is deployed on the server (Sun Application Server).
StackTrace (after jsight's suggestion):
>Exception occurred in target VM: com.sun.enterprise.naming.java.javaURLContext.<init>(Ljava/util/Hashtable;Lcom/sun/enterprise/naming/NamingManagerImpl;)V
java.lang.NoSuchMethodError: com.sun.enterprise.naming.java.javaURLContext.<init>(Ljava/util/Hashtable;Lcom/sun/enterprise/naming/NamingManagerImpl;)V
at com.sun.enterprise.naming.java.javaURLContextFactory.getObjectInstance(javaURLContextFactory.java:32)
at javax.naming.spi.NamingManager.getURLObject(NamingManager.java:584)
at javax.naming.spi.NamingManager.getURLContext(NamingManager.java:533)
at javax.naming.InitialContext.getURLOrDefaultInitCtx(InitialContext.java:279)
at javax.naming.InitialContext.lookup(InitialContext.java:351)
at gov.hud.pih.eiv.web.EjbClient.EjbClient.getUserManager(EjbClient.java:34)
I think you want to access an EJB application (known as EJB module) from a web application in Sun Application Server, right ?
ok, let's go.
When you deploy an EJB into an application server, the application server gives it an address - known as global JNDI address - as a way you can access it (something like your address). It changes from an application server to another.
In JBoss Application Server, you can see global JNDI address (after starting it up) in the following address
http://127.0.0.1:8080/jmx-console/HtmlAdaptor
In Sun Application Server, if you want to see global JNDI address (after starting it up), do the following
Access the admin console in the following address
http://127.0.0.1:4848/asadmin
And click JNDI browsing
If your EJB IS NOT registered right there, there is something wrong
EJB comes in two flavors: EJB 2.1 and EJB 3.0. So what is the difference ?
Well, well, well...
Let's start with EJB 2.1
Create a Home interface
It defines methods for CREATING, destroying, and finding local or remote EJB objects. It acts as life cycle interfaces for the EJB objects. All home interfaces have to extend standard interface javax.ejb.EJBHome - if you a using a remote ejb object - or javax.ejb.EJBLocalHome - if you are using a local EJB object.
// a remote EJB object - extends javax.ejb.EJBHome
// a local EJB object - extends javax.ejb.EJBLocalHome
public interface MyBeanRemoteHome extends javax.ejb.EJBHome {
MyBeanRemote create() throws javax.ejb.CreateException, java.rmi.RemoteException;
}
Application Server will create Home objects as a way you can obtain an EJB object, nothing else.
Take care of the following
A session bean’s remote home interface MUST DEFINE ONE OR MORE create<METHOD> methods.
A stateless session bean MUST DEFINE exactly one <METHOD> method with no arguments.
...
throws clause MUST INCLUDE javax.ejb.CreateException
...
If your Home interface extends javax.ejb.EJBHome, throws clauses MUST INCLUDE the java.rmi.RemoteException. If it extends javax.ejb.EJBLocalHome, MUST NOT INCLUDE the java.rmi.RemoteException.
...
Each create method of a stateful session bean MUST BE NAMED create<METHOD>, and it
must match one of the Init methods or ejbCreate<METHOD> methods defined in the session
bean class. The matching ejbCreate<METHOD> method MUST HAVE THE SAME NUMBER AND TYPES OF ARGUMENTS. The create method for a stateless session bean MUST BE NAMED create but need not have a matching “ejbCreate” method.
Now create an business interface in order to define business logic in our EJB object
// a remote EJB object - extends javax.ejb.EJBObject
// a local EJB object - extends javax.ejb.EJBLocalObject
public interface MyBeanRemote extends javax.ejb.EJBObject {
void doSomething() throws java.rmi.RemoteException;
}
Now take care of the following
If you are using a remote EJB object, remote interface methods MUST NOT EXPOSE local interface types or local home interface types.
...
If your Home interface extends javax.ejb.EJBObject, throws clauses MUST INCLUDE the java.rmi.RemoteException. If it extends javax.ejb.EJBLocalObject, MUST NOT INCLUDE the java.rmi.RemoteException.
Now our EJB
public class MyBean implements javax.ejb.SessionBean {
// why create method ? Take a special look at EJB Home details (above)
public void create() {
System.out.println("create");
}
public void doSomething() throws java.rmi.RemoteException {
// some code
};
}
Now take care of the following
It MUST IMPLEMENTS javax.ejb.SessionBean. It defines four methods - not shown above: setSessionContext, ejbRemove, ejbPassivate, and ejbActivate.
Notice our bean DOES NOT IMPLEMENT our business interface because of EJB specification says:
For each method defined in the interface, there must be a matching method in the session bean’s class. The matching method must have:
The same name
The same number and types of arguments, and the same return type.
All the exceptions defined in the throws clause of the matching method of the session
bean class must be defined in the throws clause of the method of the local interface.
And YOU HAVE TO DECLARE a ejb-jar.xml file according to
<?xml version="1.0" encoding="UTF-8"?>
<ejb-jar xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/ejb-jar_2_1.xsd" version="2.1">
<enterprise-beans>
<session>
<ejb-name>HelloWorldEJB</ejb-name>
<home>br.com.MyBeanRemoteHome</home>
<remote>br.com.MyBeanRemote</remote>
<local-home>br.com.MyBeanLocalHome</local-home>
<local>br.com.MyBeanLocal</local>
<ejb-class>br.com.MyBean</ejb-class>
<session-type>Stateless</session-type>
<transaction-type>Container</transaction-type>
</session>
</enterprise-beans>
</ejb-jar>
If you do not have a local EJB object remove from the deployment descriptor above
<local-home>br.com.MyBeanLocalHome</local-home>
<local>br.com.MyBeanLocal</local>
If you do not have a remote EJB object remove from the deployment descriptor above
<home>br.com.MyBeanRemoteHome</home>
<remote>br.com.MyBeanRemote</remote>
And put in META-INF directory
Our jar file will contain the following
/META-INF/ejb-jar.xml
br.com.MyBean.class
br.com.MyBeanRemote.class
br.com.MyBeanRemoteHome.class
Now our EJB 3.0
// or #Local
// You can not put #Remote and #Local at the same time
#Remote
public interface MyBean {
void doSomething();
}
#Stateless
public class MyBeanStateless implements MyBean {
public void doSomething() {
}
}
Nothing else,
In JBoss put jar file in
<JBOSS_HOME>/server/default/deploy
In Sun Application Server access (after starting it up) admin console
http://127.0.0.1:4848/asadmin
And access EJB Modules in order to deploy your ejb-jar file
As you have some problems when deploying your application in NetBeans, i suggest the following
Create a simple Java library PROJECT (a simple jar without a main method)
Add /server/default/lib (contains jar files in order you retrieve your EJB's) jar files to your Java application whether you are using JBoss (I do not know which directory in Sun Application Server)
Implement code above
Now create another war PROJECT
Add our project created just above and add <JBOSS_HOME>/client (contains jar files in order to access our EJB's). Again i do not know which directory in Sun Application Server. Ckeck out its documentation.
See its global mapping address as shown in the top of the answer
And implement the following code in your Servlet or something else whether you are using JBoss
public static Context getInitialContext() throws javax.naming.NamingException {
Properties p = new Properties();
p.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
p.put(Context.URL_PKG_PREFIXES, " org.jboss.naming:org.jnp.interfaces");
p.put(Context.PROVIDER_URL, "jnp://127.0.0.1:1099");
return new javax.naming.InitialContext(p);
}
Or the following whether you are using Sun Application Server - put the file appserv-rt.jar (I do not know which past contain appserv-rt.jar in Sun Application Server) in your classpath
public static Context getInitialContext() throws javax.naming.NamingException {
return new javax.naming.InitialContext();
}
In order to access your EJB in our Servlet or something else
MyBeanRemote myBean = (MyBeanRemote) getInitialContext().lookup(<PUT_EJB_GLOBAL_ADDRESS_RIGHT_HERE>);
myBean.doSomething();
regards,
Last two answers are both correct in that they are things you need to change/fix. But the NoSuchMethodError you see is not from your code, nor from things trying to find your code (would produce some kind of NoClassDefFoundException, I think, were this the case). This looks more like incompatible versions of the JNDI provider provided by the container, and what the JNDI implementation in the Java library wants. That's a pretty vague answer, but, would imagine it is solvable by perhaps upgrading your application server, and, ensuring you aren't deploying possibly-stale copies of infrastructure classes related to JNDI with your app, that might interfere.
First, fix your web.xml and add the Remote Interface in it:
<ejb-ref>
<description>Sample EJB</description>
<ejb-ref-name>SampleBean</ejb-ref-name>
<ejb-ref-type>Session</ejb-ref-type>
<home>com.SampleHome</home>
<remote>com.Sample</remote> <!-- the remote interface goes here -->
</ejb-ref>
Then, regarding the java.lang.NoSuchMethodError, Sean is right, you have a mismatch between the version of the app server "client library" you are using inside NetBeans and the app server version (server-side). I can't tell you exactly which JARs you need to align though, refer to the Sun Application Server documentation.
PS: This is not a direct answer to the problem but I don't think you're currently passing any useful properties when creating your initial context with the results of the call to System.getProperties(), there is nothing helpful in these properties to define the environment of a context (e.g. the initial context factory). Refer to the InitialContext javadocs for more details.