Message level Jax-WS service - java

I'm trying to create a WebService stub. I like to react to all of the request in one single place. I have a sample value generator, which handles the type of the request and creates a sample response, so I don't need the code-generation things with a lots of classes. Only a really simple one.
I have found http://jax-ws.java.net/nonav/2.2.1/docs/provider.html WebServiceProvider which is exactly for getting raw SOAP messages, and create a response in a single place.
The main problem is I'm new to this magical EE world :) and I simply can not start WebServiceProvider sample anyway.
I have Spring, SpringSource ToolSuit, Axis installed/configured, all of the other things are working.
Thank you all for your help, and please excuse me if the question is too simple for you. Maybe I just did not find/read something.
M.

Finally I have found the solution (thanks for the help from my workmates).
If you are using JAX-WS, there is a simple solution.
You need a sun-jaxws.xml in your WEB-INF folder containing the following:
<?xml version="1.0" encoding="UTF-8"?>
<endpoints xmlns="http://java.sun.com/xml/ns/jax-ws/ri/runtime" version="2.0">
<endpoint
name="RawWS"
implementation="com.stg.pack.MyServiceProvider"
url-pattern="/HotelServices200631"/>
</endpoints>
And you need a com.stg.pack.MyServiceProvider class which looks like:
package com.stg.pack;
#ServiceMode(value = Service.Mode.MESSAGE)
#WebServiceProvider(portName = "ThePortNameOfWebService",
serviceName = "TheNameOfWebService",
targetNamespace = "http://www.example.com/target/namespace/uri")
public class MyServiceProvider implements Provider<SOAPMessage> {
#Override
public SOAPMessage invoke(SOAPMessage request) {
SOAPMessage result = null;
// create response SOAPMessage
return result;
}
}
And before I forget, you need to define some things in web.xml:
<listener>
<listener-class>
com.sun.xml.ws.transport.http.servlet.WSServletContextListener
</listener-class>
</listener>
<servlet>
<servlet-name>RawWS</servlet-name>
<servlet-class>
com.sun.xml.ws.transport.http.servlet.WSServlet
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>RawWS</servlet-name>
<url-pattern>/TheNameOfWebService</url-pattern>
</servlet-mapping>
If you use it like this, all of the request are handled by the invoke method.

you basically must deploy your provider to some sort of Container. developing in J/EE basically mandates that you compile some sort of EAR or WAR or JAR and tell an app server to deploy it (be that app server a JBOSS, glassfish, Weblogic, Websphere, Tomcat, etc).
Have you tried doing this?
it also may be possible to test your provider using the javax.xml.ws.Endpoint class, although I have to admit I've never chosen to per-sue this in favor of deploying to an app server.

Related

About Welcome Page and Accessing Web Service Methods

I have a problem with configuration ( or basic understanding how things work at background). I create a JAVAEE project by checking Web application and ReSt api checkbox ( in intellij with glassfish 5.0). I have sample code below which web methods work but welcome page does not work. My web.xml and sample web service methods are below.
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>Jersey Web Application</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>test</param-value>
</init-param>
<init-param>
<param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
<param-value>true</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey Web Application</servlet-name>
**<url-pattern>/ *</url-pattern>**
</servlet-mapping>
#Path("/RestTest")
public class TestString {
#Context
ServletContext context;
#GET
#Path("insertdb/{param1}/{param2}")
#Produces(MediaType.APPLICATION_JSON)
public Object writeToDb( #PathParam("param1") String param1
,#PathParam("param2") String param2){
try{
String password= context.getInitParameter("DbPassword");
Class.forName("org.mariadb.jdbc.Driver");
Connection dbCon = DriverManager.getConnection(
"jdbc:mariadb://xxx/testdb", "root", password);
PreparedStatement stmt=dbCon.prepareStatement(
"INSERT INTO TestTable VALUES(?,?)");
stmt.setString(1,param1);
stmt.setString(2,param2);
stmt.executeUpdate();
dbCon.close();
return "Success";
}catch(SQLException | ClassNotFoundException ex){
return ex.toString();
}
}
#GET
#Path("sum/{sum1}/{sum2}")
#Produces(MediaType.TEXT_HTML)
public String calculateSum(#PathParam("sum1") int param1
,#PathParam("sum2") int param2){
return ""+(param1 + param2);
}
If i change this line url-pattern "/*" to "/"
then welcome page is accessible but not methods.
Thus what i want is, having a welcome page which i will use for documentation for my web services(i dont want SOAP) and web methods must work by adding / to base url. How can i achieve that and what is difference between /* and /
See here for explanation of differences:
What is url-pattern in web.xml and how to configure servlet
Generally for a rest api it is best to use a path specific to all rest calls, for instance http://localhost/mywebapp/rest/...
Something like:
<servlet-mapping>
<servlet-name>jersey-servlet/servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
You only want jersey serving particular URLs when it is bundled in a WAR that also includes html pages.
To answer your question, difference between "/" and "/*"
A mapping that contains the pattern "/" matches a request if no other pattern matches. This is the default mapping. The servlet mapped to this pattern is called the default servlet. The default mapping is often directed to the first page of an application. Example :
Both requests will display same contents from index.jsp
http://myhost.com/index.jsp
and
http://myhost.com/
Now, a mapping that contains "/*" overrides all other servlets, including all servlets provided by the servlet container such as the default servlet and the JSP servlet. Whatever request you fire, it will end up in that servlet. This is thus a bad URL pattern for servlets.
Possible solution for your issue
Change the URL pattern to specific instead of default pattern.
<servlet>
<servlet-name>webservice</servlet-name> //servlet name
<servlet-class>com.rest.MyRestServlet</servlet-class> //servlet class
</servlet>
<servlet-mapping>
<servlet-name>webservice</servlet-name> //servlet name
<url-pattern>/RestTest/*</url-pattern> //all webservice request
</servlet-mapping>
All the web service request are accessible through
http://myhost.com/RestTest/
You may also be interested to look
What is URL-pattern in web.xml and how to configure servlet
Basics of Java Servlet
Servlet configuration and url-pattern
As you highlighted, your problem revolves around those four lines:
<servlet-mapping>
<servlet-name>Jersey Web Application</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
As Jim Weaver mentioned, it's a matter of url-pattern.
Solution(s)
You may consider three solutions (from the most-preferred to least-preferred):
dedicated REST URL: the easiest way is to have a dedicated url-pattern such as /rest/* for your web services. You can benefit some assets such as url hierarchy or you can easily implement a security framework over it.
URL rewriting may be an option and this answer suggests some library. I haven't tested those libraries myself
Page redirection can be an option to go around REST filtering but in the specific case of having the url-pattern at /*, I have to say I'm not sure if it's working for the reason I'll explain in next section
now a bit of explanation of what happened
Why setting the url-pattern at /* prevent from accessing the welcome page?
Actually, it's not only the welcome page that is not accessible: it's all the resources under the defined url-pattern. Whatever get in touch with REST stays with REST... Here is the schema taken from JSR 339 Appendix C:
With a GlassFish 5.0, I guess you're using JAX-RS 2.1 (JSR 370) but the sections I'm quoting have the same content
Without entering into detail, it is visible that only ContainerRequest Filters are executed in the process. Especially, it's worthy to notice that after Request Matching, requests are not forwarded to any servlet in a sense that standard resources are not reachable, unless specified by the REST method.
It's also worthy to highlight the fact the servlet filters are executed beforehand (leveraging this point is absolutely vital for managing security for example). I did not find back the source proving this point but I know it's somewhere on the web ^^.
Request matching is defined at section 3.7.2. In a nutshell, it is in three steps where the first one is the most important for your question, especially at step D:
Identify a set of candidate root resource classes matching the request
c. ...
d. If [the set of classes whose path matches the request URL] is empty then no matching resource can be found, the algorithm terminates and an implementation MUST generate a NotFoundException (404 status) and no entity
e. ...
highlights are mine.
The two last steps are
Obtain a set of candidate resource methods for the request
Identify the method that will handle the request
TL;DR
What happened when you set <url-pattern>/*<url-pattern> and tries to access to your welcome page (or any page actually):
Your server receives the GET request
If there are filters (such those from a security framework), there are executed
REST enters the scene
Pre Match filters are executed (none if your case)
Fetch your root resources classes (in your example, all classes in the test package)
Find if one of those class match the request URL
None are found, a 404 status is returned
To avoid unnecessary URL conflicts, the best options would be having a dedicated URL for your REST methods
If you mention in web xml like following all the request receive by 'Jersey Web Application' servlet. so request to index.jsp also redirect to 'Jersey Web Application' servlet
<servlet-mapping>
<servlet-name>Jersey Web Application</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
To avoid this add some prefix to the url to separate rest request like following
<servlet-mapping>
<servlet-name>Jersey Web Application</servlet-name>
<url-pattern>rs/*</url-pattern>
</servlet-mapping>

Java + TomEE. Websockets and Servlets in one project?

I'm writing a simple game with JavaEE Websocket technology. Using JSR356, my server-side socket class looks like following:
#ServerEndpoint(
value = "/sock",
decoders = { SocketDecoder.class }
)
public class CardsSocket {
....
#OnMessage
public void onMessage(final SocketInput message, final Session session) {
...
}
...
}
It works perfectly fine, and has no issues. But then I decided to create also some web page for info and stuff. So, without changing anything on previous class, I have created a new one:
#ServerEndpoint(value = "/cards")
public class CardsWebPage extends HttpServlet {
#Override
public void doGet(...) {
...
}
}
And configured web.xml file in WEB-INF directory.
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1"
metadata-complete="true">
<servlet>
<servlet-name>CardsWebPage</servlet-name>
<servlet-class>server.CardsWebPage</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CardsWebPage</servlet-name>
<url-pattern>/cards</url-pattern>
</servlet-mapping>
</web-app>
And there began troubles. My servelet works - browser shows page on localhost:8080/cards, but client-side socket class can no longer initiate - it falls with Exception:
"javax.websocket.DeploymentException: The HTTP response from the server [HTTP/1.1 404 Not Found] did not permit the HTTP upgrade to WebSocket"
, and nothing seems to fix it. Have I missed some documentation? Is it impossible for a single project to contain both servlets and websocket classes? Because, if I delete web.xml file, then sockets are starting to work like before. Server startup logs containing no warnings or errors in both cases.
Yeah, perhaps sparks is right, and I should simply deploy multiple projects.
Hi why decorating CardsWebPage with #ServerEndpoint? Nothing or if you can to get rid of web.xml #WebServlet should be fine.

Error trying to call method from server on GWT

I'm trying to call a method from my server side whose signature is
public Integer method()
but when I redid all the steps used on the StockWatcher tutorial to call it, I'm getting a 404 error which says this is the URL
<p>RequestURI=/com.medtronic.empattendance.EmployeeAttendance/empQueries</p>
I'm not sure what the correct URL should be, but this is the incorrect URL.
my web.xml says this on servlets
<servlet>
<servlet-name>empQueryServerImpl</servlet-name>
<servlet-class>com.medtronic.empattendance.server.EmpQueryServerImpl</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>empQueryServerImpl</servlet-name>
<url-pattern>/empattendance/empQueries</url-pattern>
</servlet-mapping>
Where am I going wrong?
There is an alternative: Use the #RemoteServiceRelativePath (javadoc) annotation on your RPC class (The interface extending RemoteService, not the Async one).
Assuming your GWT app is /empattendance:
#RemoteServiceRelativePath("empQueries")
public interface EmpQueryServer extends RemoteService {
// your methods
}
I have solved it:
I had <url-pattern>/empattendance/empQueries</url-pattern> which was based off the tutorial, but digging deeper I found out I needed to use the full package name.
<url-pattern>/com.myCompany.empattendance.EmployeeAttendance/empQueries</url-pattern>

How to initialize Java EE 5 JAX-WS 2.0 Web Service with Parameters

Application configuration:
Web application using java first method of creating JAX-WS 2.0 Web Services with annotations.
WebLogic 10.3
My Requirements
The requirements I have are to deploy a single web service implementation class, but change logic based on the URL from which the service was accessed.
Question:
I'm assuming a good way to do this is to deploy different mappings in web.xml and initialize them with different parameters. Is there a better way?
What is the best way to switch logic off the URL from which the web service was accessed? Should I try to configure two servlet mappings in web.xml with initialization parameters (tried, but couldn't get it to work), or should I parse the URL in the service impl? Any other alternatives?
What I've Tried (but didn't work)
I have tried adding the <init-param> in the <servlet> element in web.xml. However, can't get to the ServletConfig object inside the web service to retrieve the param. The web service does not have all the functionality of a standard Servlet (even if I implement Servlet or ServletContextListener). I only have access to the WebServiceContext (it seems) and from there I can only get <context-param> elements--but I would need <init-param> elements instead.
In web.xml, I enter two <servlet> elements using the same Java class, but which map to two different URLs as follows. Notice how the "source" param is different in each Servlet mapping.
<servlet>
<servlet-name>Foo</servlet-name>
<servlet-class>com.Foo</servlet-class>
<init-param>
<param-name>source</param-name>
<param-value>1</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>Foo</servlet-name>
<url-pattern>/Foo</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>Bar</servlet-name>
<servlet-class>com.Foo</servlet-class>
<init-param>
<param-name>source</param-name>
<param-value>2</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>Bar</servlet-name>
<url-pattern>/Bar</url-pattern>
</servlet-mapping>
You very well may have, but did you try using MessageContext at runtime to determine what the source is?
#WebService
public class CalculatorService implements Calculator
{
#Resource
private WebServiceContext context;
#WebMethod
public void getCounter()
{
MessageContext mc = wsContext.getMessageContext();
// you can grab the HttpSession
HttpSession session = (HttpServletRequest)mc.get(MessageContext.SERVLET_REQUEST)).getSession();
// ...or maybe the path info is enough
String path = mc.get(MessageContext.PATH_INFO);
// the query itself should almost definitely be enough
String query = (String) mc.get(MessageContext.QUERY_STRING);
}
}
I got the idea from http://sirinsevinc.wordpress.com/category/jaxws/. Haven't tried it, though.

jax-ws on glassfish3 init method

I've created simple jax-ws (anotated Java 6 class to web service) service and deploied it on glassfish v3. The web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app>
<servlet>
<servlet-name>MyServiceName</servlet-name>
<description>Blablabla</description>
<servlet-class>com.foo-bar.somepackage.TheService</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>MyServiceName</servlet-name>
<url-pattern>/MyServiceName</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>30</session-timeout>
</session-config>
</web-app>
There is no sun-jaxws.xml in the war.
The service works fine but I have 2 issues:
I'm using apache common configuration package to read my configuration, so i have init function that calls configuration stuff.
1. How can I configure init method for jaxws service (like i can do for the servlets for example)
2. the load on startup parameter is not affecting the service, I see that for every request init function called again (and c-tor). How can I set scope for my service?
Thanks a lot,
How can I configure init method for jaxws service (like i can do for the servlets for example)
JAX-WS endpoints, both web and EJB, can have optional life-cycle methods that are automatically called if present. Any method can be used as a life-cycle method with the correct annotation:
#PostConstruct - Called by the container before the implementing class begins responding to web service clients.
#PreDestroy - Called by the container before the endpoint is removed from operation
So annotating your init() method with #PostConstruct should do the trick.
the load on startup parameter is not affecting the service, I see that for every request init function called again
Try to use the suggested annotation first. And if you are still facing unexpected behavior, post your code.
Thanks for the quick answer, Pascal.
BTW, I warmly suggest to use a "valid" servlet 2.5 or servlet 3.0 web.xml (using a version attribute in the web-app element and the xsd declaration).
I'm using 2.5 version, I just didn't paste this part in my post
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:j2ee="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.5"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<description>WebTier for the Login Manager Service</description>
<display-name>LoginManagerWAR</display-name>
<servlet>
<description>Endpoint for Login Manager Web Service</description>
<display-name>LoginManagerControllerService</display-name>
<servlet-name>LoginManagerController</servlet-name>
<servlet-class>loginmanager.controller.LoginManagerController</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>LoginManagerController</servlet-name>
<url-pattern>/LoginManagerControllerService</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>54</session-timeout>
</session-config>
The PostConstruct works fine , thank you, but load-on-startup still didn't happen.
#WebService(
name="LoginManagerController",
serviceName="LoginManagerControllerService"
)
public class LoginManagerController {
private ILoginManager manager;
#Resource
private WebServiceContext wsContext;
#PostConstruct
private void init(){
.....
}
More over, now every client request makes 2 init() calls of the webservice:
like I can see in chainsaw, first called init() of the service, then it called again and then the actually client's function (I print the hash code of the webservice class instance and it the same instance for both calls!!!):
> Message Inside init() method ... controller=31641446
> Message login manager = 11229828
> .....init of elements....blablabla.....
> Message Exiting init() method
> Message Inside init() method ... controller=31641446
> Message login manager = 32361523
The controller is the service and the manager (wich hash code has been changed from first call to the second) created inside the init () of the controller.
I failed to understand what is wrong ....
UPDATE
It seems like a to glassfish v3 related issue (maybe my env setup or glassfish configuration). I tried this war on Sailfin and Glassfish V2 and its perfectly working ....

Categories