I have a service defined as follows.
public String getData(@QueryParam("date") Date date)
I'm trying to pass a java.util.Date
to it from my client (which is jaxrs:client of CXF, not a generic HTTP client or browser).
My service receives the date as Thu Mar 01 22:33:10 IST 2012
in the HTTP URL. Since CXF won't be able to create a Date
object using this String, my client receives a 404 error.
I tried using a ParameterHandler
on the service side, but I still can't parse it successfully because I'm not expecting the date in any specific format.
As per this post, passing a Date
is supposed to work out of the box, but I can't seem to get the basic case working. Am I required to do anything in order to successfully pass a Date object from my client to service? Appreciate any help.
Thanks
The problem is that JAX-RS dictates that parameter unbundling be done in one of two ways:
valueOf(String)
method.In your case, the Date is being unbundled via its
Date(String)
constructor, which cannot handle the input format your client is sending. You have a couple options available to remedy this:Option 1
Get your client to change the format of the date before they send it. This is the ideal, but probably the hardest to accomplish!
Option 2
Handle the crazy date format. The options for this are:
Change your method signature to accept a string. Attempt to construct a Date object out of that and if that fails, use your own custom SimpleDateFormat class to parse it.
Define your own parameter class that does the logic mentioned above. Give it a string constructor or static
valueOf(String)
method that invokes the logic. And an additional method to get the Date when all is said and done.Or finally, you can register a parameter handler for dates. Where its logic is simply the same as mentioned for the other options above. Note that you need to be using at least CXF 2.5.3 in order to have your parameter handler evaluated before it tries the default unbundling logic.
Using a custom DateParam class seems the safest option. You can then base your method signatures on that and implement the ugly conversion logic inside the valueOf() method or the class constructor. It is also more self-documenting than using plain strings
As
@Perception
suggests in option two, you can handle the date. But you should use following:You call it from within the resource as
Percepiton's answer was very useful, but
ParameterHandler
has been deprecated in Apache-cxf 3.0, see the Apache-cxf 3.0 Migration Guide:So I add an example with the
ParamConverterProvider
:The
@SuppressWarnings
is required to suppress an "unchecked or unsafe operations" warning during compilation. See How do I address unchecked cast warnings for more details.The
ParamConverterProvider
can be registred as provider. Here is how I did it:See Apache-cxf JAX-RS : Services Configuration for more information.