Earthly Powers
- All
- Fast Infoset
- General
- Java
- REST
Jersey 1.0.2 is released
We have just released version 1.0.2 of Jersey, the open source, production quality, reference implementation of the JAX-RS 1.0 API. The JAX-RS specification is available at the JCP web site and also available in non-normative HTML here.
This release will be available tomorrow (12th Feb, if all goes well) from the Glassfish v2 update center, which aligns with the release of the Glassfish Portfolio that includes the GlassFish v2.1 Enterprise Server.
It will be available from the Glassfish v3 update center once we resolve some dependency issues.
To get started with Jersey read the getting started document. For an overview of JAX-RS features visit the Jersey wiki and read the overview document. To understand more about what Jersey depends on read the dependencies document. The following JavaDoc is available:
- Client, Server, WADL, JSON APIs.
- Spring integration API.
- MIME Multipart API.
- Client using Apache HTTP client API.
- Atom with Apache Abdera API.
This release has many bug fixes, you can see the change log here, as well as the following improvements and features:
- The JSON with JAXB "natural" convention.
Jakub has worked closely with the JAXB team so that the producing/consuming of JAXB to/from JSON uses information from the JAXB model. This makes for JSON from JAXB that is more "natural", easier to consume, and requires less configuration on the part of the developer. As part of this work we replaced our own JSON parsing and writing functionality with Tatu's JSON library Jackson.
For backwards compatibility we have retained the previous "mapped" convention as the default convention, but this is easy to change using the new JSON configuration, but i will leave such explanations for Jakub to blog about. In the next release we will probably deprecate the "mapped" convention. - JSON with padding provider.
Jakub has included a JSON with Padding (JSONP) provider for those wishing to embed JSON within a JavaScript "callback" function. This provider will also work with JSON and XML media types. See the JSONP sample for more details. - Resource method specific filters.
I finally got around to implementing resource specific filters. Request and response filters can now be associated with sub-resource locator and resource methods. For more details see the JavaDoc here. This functionality is used to implement support for @RolesAllowed using the RolesAllowedResourceFilterFactory. - Atom Abdera support.
Craig McClanahan has added support for producing and consuming of Atom Entry and Feed Java types of the Apache Abdera project. An injectable helper class, ContentHelper, is supplied to support the getting and setting of the content part of an Atom entry reusing the registered message body readers and writers. Craig has also provided some really nice examples showing a simple client and server. The server reuses the @RolesAllowed support for some authorization logic based on the user principal and the URI. For more details refer to the AtomPub Contacts Client and Server samples. - Implicit produces.
With James Strachan's prompting and great help (discussions, issues and patches) i have implemented support for @ImplicitProduces on resource classes. This allows one to use the implicit model view controller approach for JSPs producing HTML as presented in the bookstore sample while allowing explicit methods for other media types say XML or JSON. Unfortunately we could not resolve some issues in time for this release, associated with the maven unit test plugin and embedded Glassfish, to update the bookstore sample. - Servlet as a filter.
As part of James's "JAX-RS as the one Java web framework to rule them all?" i have modified the Servlet support such that one can register the Servlet artifact as a Servlet or a Filter, see here and here for more details. The advantage of the latter is that it is much easier to support filters declared before the Jersey filter that redirect to say static content or redirect to other Web frameworks. James has already provided a patch to the Jersey filter to support the returning of static content, which will be integrated into the 1.0.3-SNAPSHOT next week. - Client using Apache HTTP client.
Jorge Williams contributed support for using the Jersey Client API with the Apache HTTP client (as opposed to using HttpURLConnection). See here for more details. - Pavel Bucek has added support for SSL configuration of the Client API when using HttpURLConnection. See here for more details.
For the next release, 1.0.3, scheduled for March/April 2009, we plan to include the following contributions (these were previously considered for 1.0.2 but were not stable enough):
- Guice 2.0 integration.
Gili Tzabar has contributed Guice support as a patch and we continue to refine this. The patch will go into the 1.0.3-SNAPSHOT next week. It is understood that the Guice 2.0 APIs are stable and i have found a maven repository where Guice 2.0 snapshot jars are available. This should give us enough time between now and the 1.0.3 release to refine the support. - Test framework.
Naresh has been working hard on the jersey test framework in another branch. Unfortunately it was not quite ready for the 1.0.2 release and we need to depend on a stable API for embedded Glassfish, which is currently being designed. Once the framework is in place it will allow us to write tests that are capable of being deployed on different containers.
For feedback send email to:
users@jersey.dev.java.net (archived here)
or log a bugs/features here.
Posted at 03:20PM Feb 12, 2009 by Paul Sandoz in REST | Comments[2]
A Christmas present for Jersey ant users?
!/bin/bash
version=1.0.1
function getJerseyModule {
curl http://download.java.net/maven/2/com/sun/jersey/$1/${version}/{$1-${version}.jar} -o "#1"
}
for module in jersey-core jersey-server jersey-client; do
getJerseyModule $module
done
curl http://download.java.net/maven/2/javax/ws/rs/jsr311-api/1.0/{jsr311-api-1.0.jar} -o "#1"
curl http://repo1.maven.org/maven2/asm/asm/3.1/{asm-3.1.jar} -o "#1"
I jest of course :-) but there is a serious point.
Since we moved to maven we longer provide a zip of Jersey. This has advantages because we no longer have to get approval to bundle and then bundle third party jars, especially for samples that could depend on many things, making for a rather large download.
But perhaps for ant users we can make it a little easier to obtain the core Jersey jars and dependencies. What do Jersey ant users prefer?
- download a script that when run downloads the core Jersey jars and dependencies; or
- download a zip containing the same jars as would be downloaded in 1).
Posted at 03:12PM Dec 19, 2008 by Paul Sandoz in REST | Comments[4]
Devoxx slides and examples for the JAX-RS presentation
A PDF of my Devoxx presentation can be found here.
The simple example project i used to demonstrate some JAX-RS features can be found here. This is a maven project. It can be loaded into NetBeans 6.5 if using the maven plugin.
The EJB example can be found here. This is a NetBeans 6.5 project using Jersey 1.0 as shipped with NetBeans 6.5. Note that this currently relies on Glassfish only specific behaviour and is intended as a demostration of where JAX-RS EE 6 functionality is heading.
The simple Security example leveraging Web container security, that i had no time to present, can be found here. This is a NetBeans 6.5 project using Jersey 1.0 as shipped with NetBeans 6.5. I wish i had time to present this as it would have given me the opporunity to have a great rant at the limited support for HTTP authentication in browsers such as Firefox. The user could be so much more in control of authenticated sessions...
Posted at 04:02PM Dec 15, 2008 by Paul Sandoz in REST | Comments[4]
Jersey, Glassfish, and EJBs as root resources
Jersey supports EJB 3.0 beans as root resources as follows:
- Annotate a local or remote interface with @Path and annotate methods as appropriate; and
- Ensure that the local or remote interface in 1) is registered by file/directory or package scanning.
The registration mechanism in 2) is no different for registering non-EJBs. The caveat: it currently only works with Glassfish, which supports JNDI lookup of an EJB reference using the fulling qualified class name of the local or remote interface.
The JSR 311 expert group is currently considering approaches to integrate JAX-RS with EJB 3.1, which should present some nice improvements, namely EJBs bundled in the war and EJBs with no interfaces. I have high hopes we can retain the current ease of use registration aspects with JAX-RS as presented here and then it should be really simple to use EJBs as POJOs in the web tier directly serving HTTP requests.
There are already some EJB 3.1 features ready in Glassfish Prelude, as highlighted by Ken, with update centre instructions from Mahesh. Now i need to find the time to experiment...
Posted at 11:23AM Dec 02, 2008 by Paul Sandoz in REST | Comments[0]
Jersey 1.0.1 is released
We have just released version 1.0.1 of Jersey, the open source, production quality, reference implementation of the JAX-RS 1.0 API. The JAX-RS specification is available at the JCP web site and also available in non-normative HTML here.
This release will be available soon from the Glassfish v2 and v3 update centers.
To get started with Jersey read the getting started document. For an overview of JAX-RS features visit the Jersey wiki and read the overview document. To understand more about what Jersey depends on read the dependencies document. For details of the Jersey API go to here.
This release has many bug fixes, you can see the change log here, as well as the following improvements and features:
- The IoC integration SPI was improved to provide a clearer and well-defined distinction between IoC-managed components and Jersey-managed components. Additionally, Jersey managed components now support @PostConstruct and @PreDestroy for all the supported Jersey-based life-cycles.
- Spring integration was improved based on IoC integration improvements. Spring-registered beans (in the XML configuration or auto-wired) that are root resource or provider classes are automatically registered. See the JavaDoc here for more details on how to integrate with Spring.
- Craig McClanahan has contributed a high-level MIME multipart API. This makes it easier to read and write MIME body parts using the same mechanisms as reading and writing entities of requests and responses. We expect to leverage this API for further ease of use improvements in future releases.
- Jakub added two maven archetypes for quickly creating maven projects: a quick start Web application archetype using Glassfish and embedded Glassfish; and a quick start Grizzly application archetype. See Jakub's enterprise tech tip and Arun's blog entry for more details.
- A Scala-based Web application sample and a very simple Groovy-based embedded Grizzly server sample are now included in the samples.
For the next release, 1.0.2 scheduled for Jan/Feb 2009, we plan to include the following contributions:
- Utilizing the Jersey Client API with the Apache HTTP client, contributed by Jorge Williams.
- Integration with Guice, contributed by Gili Tzabari.
For feedback send email to:
users@jersey.dev.java.net (archived here)
or log a bugs/features here.
Posted at 05:05PM Dec 01, 2008 by Paul Sandoz in REST | Comments[3]
Jersey samples
The samples supplied with Jersey are on the java.net maven repository as a single zip file or individually (browse from here).
All the of samples are capable of being executed from the command line or from NetBeans 6.5 beta/dev build (with the maven plug-in configured to an external maven distribution version 2.0.9 or greater). Maven makes it easy to distribute the samples without redistributing third party dependencies, such as Grizzly, GlassFish embedded, Spring, and Scala, some of which can be rather large.
Some samples have unit tests that avail of the Jersey client API. This serves a number of purposes:
- How to use the Jersey client API;
- How to deploy in embedded scenarios using Grizzly and GlassFish;
- How to develop functionality tests for resources using JUnit; and
- Limit or remove manual testing of the samples.
We plan to automate the testing of all samples and from this experience we plan to create a useful JAX-RS/Jersey testing framework that is capable of abstracting from the actual HTTP container used to deploy resource classes. The ultimate goals are to make it easier to test and to automate everything so that we can test continuously via Hudson. Potentially we can then spin stable releases as fast as Hudson slaves can test.
A sample i particularly like and i recently added is Sparklines, which was inspired by Joe Gregorio's Sparklines service and python implementation. Sparklines, "as defined by Tufte, are intense, simple, word-sized graphics".
Here is a snippet of the Sparklines resource class:
@Path("/")
@Produces("image/png")
public class SparklinesResource {
List<Integer> data;
@DefaultValue("20") @QueryParam("height") int imageHeight;
Interval limits;
EntityTag tag;
public SparklinesResource(
@QueryParam("d") IntegerList data,
@DefaultValue("0,100") @QueryParam("limits") Interval limits,
@Context Request request,
@Context UriInfo ui) {
if (data == null)
throw new WebApplicationException(400);
this.data = data;
this.limits = limits;
if (!limits.contains(data))
throw new WebApplicationException(400);
this.tag = computeEntityTag(ui.getRequestUri());
if (request.getMethod().equals("GET")) {
Response.ResponseBuilder rb = request.evaluatePreconditions(tag);
if (rb != null)
throw new WebApplicationException(rb.build());
}
}
Besides being a fun application with a practical use it uses a whole bunch of JAX-RS features in one Java class: query parameter with default values, application-specific classes for query parameters, parameters on fields, throwing exceptions in constructors, and preconditions where entity tags are generated from the information in the request URI.
For those wanting to move beyond 1.0 i have just added a simple Groovy sample to the 1.0.1-SNAPSHOT. It needs to be improved and I ain't that familiar with Groovy so if any one wants to contribute something more substantial to show off Groovy, JAX-RS and Jersey let me know.
And... on a tangential topic related to languages i have been taking a little look at Clojure. There is a very thought provoking presentation on line. For those of us not that familiar Lisp the syntactical "explosion" of braces of Clojure can be a bit overwhelming compared to Java at first, but, if one looks at Clojure's Java interoperation and then compares Clojure code with Java code with the following consideration, think of curly braces as just braces, then the Clojure syntax is OK and can be very conscise yet still readable, and it is often just the order of where "." and braces occur that changes. I also took a little look at the code, for what Clojure does the set Java code is rather small, often strange (as Rich Hickey says he tries to apply functional idioms to Java code), and has some very interesting implementatons of persistent (in the functional sense) data structures.
Posted at 05:41PM Oct 16, 2008 by Paul Sandoz in REST | Comments[4]
Jersey 1.0 is released
We have just released version 1.0 of Jersey, the open source, production quality, reference implementation of the JAX-RS 1.0
API. The JAX-RS specification is available at the JCP web site and also available in non-normative HTML here.
To get started with Jersey read the getting started document. For an overview of JAX-RS features visit the Jersey wiki and read the overview document. To understand more about what Jersey depends on read the dependencies document. For details of the Jersey API go to here.
Jersey 1.0 is released to the Java.Net maven repository. Jars, source, JavaDoc and samples are all available from the following base URI:
All the samples can be obtained individually or as one zip file.
Jersey will be available soon from the Glassfish v2 and v3 update centers. And will be available in the Netbeans 6.5 release.
I decided to forgo a cycling themed picture this time and instead present a Castell. To quote Eduardo: "Many people need to do their tasks very well to build such a big castell". While the JAX-RS and Jersey castells may not require as many people as Glassfish i think the analogy still applies. Perhaps one could view Glassfish as an Escher like castell where each component is a castell itself? in any case i digress!
I would like to thank everyone that has contributed to the JAX-RS API and/or Jersey, whether it be the expert group members, comments on JAX-RS from external individuals (emails and blogs) and the many developers living on the edge trying out the Jersey early access releases, providing feedback and contributing code.
We have a better API because of the JCP process. With at least five different implementations of JAX-RS in development, four of them open source as of writing, the API was tested early and often.
We have a better reference implementation because we are open source, released early and often, and are responsive to the community.
What's next? In terms of JAX-RS the expert group will be starting a maintenance release to align with EE 6. In terms of Jersey here are some current aspects off the top of my head:
- improve the boundaries between Jersey modules (for OSGi) and further modularize, this will require name changes to some API packages;
- better MIME multipart support;
- investigate further comet/AJAX integraton; and
- improve the integration with IoC frameworks. It is hard to be abstract from any IoC framework.
there is much more and i plan to create a more complete set of short and long term tasks in the next couple of weeks. If you have ideas send email to:
or log a feature here.
Posted at 04:38PM Oct 13, 2008 by Paul Sandoz in REST | Comments[13]
Jersey 0.9 is released
We have just released version 0.9 of Jersey. This aligns with the 0.9 release of the JAX-RS
API
and the editors draft.
For this and further releases the mechanism to obtain Jersey is different. There is no longer one zip file to download. Jersey is now modularized and mavenized thanks to the hard work of Jakub. Jars, source, JavaDoc and samples are all available from the Java.Net maven repo at the following base URI:
All the samples can be obtained individually or as one zip file.
Now it is much easier for maven developers to use Jersey. But as a consequence it is a little harder for non-maven developers to use Jersey. To aid such developers we provide a detailed dependencies document and a bundled jar containing all jersey-related functionality that was previously available in the 0.8 release.
In this release i managed to add support for generic server-side filters and a specific filter to support the "X-HTTP-Method-Override" HTTP header for clients that do not support HTTP PUT and DELETE. Martin has integrated JavaDoclet WADL support. See the example here for more details.
In the past week we have been doing things in parallel and i have been working on the 0.10 implementation before 0.9 is released. We need to step up the pace as the 1.0 finishing line is just a few weeks away.
Posted at 06:08PM Aug 22, 2008 by Paul Sandoz in REST | Comments[7]
Integrating Jersey and Spring: Take 3
Just in case it got hidden in the message of the 0.8 release Jersey now supplies Spring support via the spring maven module that was contributed by Martin.
So, rather than copying some code from my blog, you can depend on this module and reference the Spring servlet:
com.sun.jersey.spi.spring.container.servlet.SpringServlet
in the web.xml. That is it. Martin describes this in more detail here. Note that after this was written some changes were made to the package names as Martin describes here.
I am quite happy with it as we managed to solve a knotty issue of referencing Spring beans in constructor/method parameters that Jersey is responsible for invoking, thus JAX-RS/Jersey-based annotated parameters can be intermixed with Spring-based annotated or referenced parameters. Having said that i think we may be able to make the integration even smoother in two areas when using Spring-based annotation configuration: 1) inferring the life-cycle Jersey requires; and 2) reusing @Autowired for constructor/method parameters.
The mechanisms by which Jersey integrates with Spring can equally apply to Guice or WebBeans or a more specialized integration.
Posted at 08:48AM Aug 18, 2008 by Paul Sandoz in REST | Comments[1]
Parameter beans
In the JAX-RS EG we modified the target of the @Query/Path/MatrixParam annotations so that fields can be annotated on resource classes or on Java beans in general. I was skeptical at first that this would be a good idea (mainly around the life-cycle aspects of resource classes), but Bill Burke convinced me and the EG it would be a good idea. For example, consider a large set of query parameters that keep repeating, having to duplicate that set as method parameters is not ideal.
I finally started experimenting with the idea of supporting such beans in Jersey. To my pleasant surprise there proved to be a rather simple and elegant solution: treat such beans as resource classes.
An InjectableProvider can operate on an annotation, say ResourceParam as follows:
@Provider public static class ResourceParamInjector implements InjectableProvider<ResourceParam, Type> { @Context ResourceContext rc; public Scope getScope() { return Scope.PerRequest; } public Injectable getInjectable(ComponentContext ic, ResourceParam a, Type t) { if (!(t instanceof Class)) return null;final Class c = (Class)t; if (c.isPrimitive()) return null; return new Injectable<Object>() { public Object getValue(HttpContext context) { return rc.getResource(c); } }; } }
Essentially the injected ResourceContext instance is created to obtain the resource class instance.
A resource class could look like this:
@Path("/") public static class Resource { public static class QueryBean { @DefaultValue("abcd") @QueryParam("foo") String foo; @DefaultValue("9999") @QueryParam("bar") int bar; }@GET public String get(@ResourceParam QueryBean qb) { return qb.foo + qb.bar; } }
The fields foo and bar on the QueryBean class behave in the same manner as if they were parameters on the method get or fields on the class Resource.
A side effect of this approach is that the QueryBean class has the same life-cycle rules of a resource class, thus one could annotate it with say @Singleton, which i am not sure is very useful (since @*Param annotations are not allowed on fields of singletons).
Posted at 05:06PM Aug 07, 2008 by Paul Sandoz in REST | Comments[0]
Modularizing Jersey
Jakub (who is now taking a well-deserved holiday) converted the Jersey project over to maven and modularized code. Converting from ant to maven is not easy, the barrier to understanding maven and its idiosyncrasies is rather high in my opinion. Once things are in place and stable i can see the benefit in terms of the build process and what it brings to developers in terms of a network-based dependency system.
We have modularize Jersey functionality into the following modules:
- jersey-core: common code shared between client and server.
- jersey-client: client-side support.
- jersey-server: server-side support.
- jersey-atom: Atom de/serialization using Rome.
- jersey-json: JSON de/serialization using Jettison and JAXB.
- jersey-bundle: contains all the above as one jar (the maven plugin has some bugs that stop the source jar and pom being correctly generated).
Further more the contributions module provides the following sub-modules:
- jersey-spring: spring support for Jersey. In your WebApp use the SpringServlet provided by this module.
- maven-wadl-plugin: improved WADL support, including recognition of JAXB and embedding JavaDoc into WADL to have full documentation associated with the code and provided by the service.
In addition the tests are available and we are converting the examples over to maven projects. There is still more modularization work to do, and as a result the boundaries between modules (mainly between jersey-core and jersey-client/server need to be improved).
Some developers may now be confused as there are two unstable versions of 0.9. The old unstable unmodularized 0.9 is available on java.net as a zip file and also from the maven repo. We have kept this around for developers that do not wish to be affected by maven issues with the new unstable modularized 0.9. The old 0.9 will be removed once we are satisfied with the functionality and stability of the new 0.9.
We have set up Hudson to continuously push 0.9 SNAPSHOT modules to the java.net maven repo when source-code changes occur. However, i have been informed that this is backed by a subversion repository so a history will be kept of all the binary files. So we probably need to switch to the Glassfish maven repo for SNAPSHOT builds as this is not subversion controlled, while using the java.net repo for stable releases.
Posted at 12:23PM Aug 06, 2008 by Paul Sandoz in REST | Comments[0]
BBC using Jersey
A recent comment on a blog entry from Jon, a developer at the BBC, says:
Thought you might be interested to hear that here at the BBC we now have a RESTFul JSR311 compliant webservice implemented using Jersey running with Jetty.
It is currently for internal use only but is part of an editorial toolset that Sports Journalists are using.
Nice, great news Jon! Maybe in some modest way Jersey will be contributing to the reporting of the Olympics :-)
Posted at 11:01AM Aug 06, 2008 by Paul Sandoz in REST | Comments[0]
Services are clients too
RESTful services can also be clients that make RESTful requests to other services. Jersey has a client API and resource classes can use that to efficiently make such requests.
Following on from my last blog entry on injection i can combine injection with a client API to make things a little easier. So i can have a resource class that does the following:
@Path("/") public static class Resource { @GET public String get( @WebResourceRef("http://localhost:9999/one") AsyncWebResource r1, @WebResourceRef("http://localhost:9999/two") AsyncWebResource r2) throws InterruptedException, ExecutionException { Future<String> c1 = r1.path("foo").get(String.class); Future<String> c2 = r2.path("bar").get(String.class);return c1.get() + c2.get(); }@GET @Path("one/{stuff}") public String getOne(@PathParam("stuff") String stuff) { return stuff; }@GET @Path("two/{stuff}") public String getTwo(@PathParam("stuff") String stuff) { return stuff; } }
The get method has two parameters that are annotated with @WebResourceRef that declares client-based URIs. I wrote an InjectableProvider for that annotation that creates instances of AsyncWebResource or WebResource (see end of this entry for complete source that should work with Jersey 0.8) based on the URI. When that method is invoked it makes two asynchronous requests, to sub-resource methods of the same resource class, and returns the result.
I think this is interesting enough to include support for this in Jersey.
import com.sun.grizzly.http.SelectorThread;
import com.sun.jersey.api.client.AsyncWebResource;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.UniformInterfaceException;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.container.grizzly.GrizzlyServerFactory;
import com.sun.jersey.api.core.HttpContext;
import com.sun.jersey.spi.inject.Injectable;
import com.sun.jersey.spi.inject.InjectableProvider;
import com.sun.jersey.spi.service.ComponentContext;
import com.sun.jersey.spi.service.ComponentProvider.Scope;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Type;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.ext.Provider;
public class Main {
@Target({ElementType.PARAMETER, ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public static @interface WebResourceRef {
String value();
}
@Provider
public static class WebResourceProvider implements InjectableProvider<WebResourceRef, Type> {
private final Client client;
public WebResourceProvider() {
this.client = Client.create();
}
public Scope getScope() {
return Scope.PerRequest;
}
public Injectable getInjectable(ComponentContext cc, final WebResourceRef wrr, Type t) {
if (!(t instanceof Class)) return null;
Class c = (Class)t;
if (WebResource.class == t) {
return new Injectable<WebResource>() {
public WebResource getValue(HttpContext c) {
return client.resource(wrr.value());
}
};
} else if (AsyncWebResource.class == t) {
return new Injectable<AsyncWebResource>() {
public AsyncWebResource getValue(HttpContext c) {
return client.asyncResource(wrr.value());
}
};
} else {
return null;
}
}
}
@Path("/")
public static class Resource {
@GET
public String get(
@WebResourceRef("http://localhost:9999/one") AsyncWebResource r1,
@WebResourceRef("http://localhost:9999/two") AsyncWebResource r2)
throws InterruptedException, ExecutionException {
Future<String> c1 = r1.path("foo").get(String.class);
Future<String> c2 = r2.path("bar").get(String.class);
return c1.get() + c2.get();
}
@GET
@Path("one/{stuff}")
public String getOne(@PathParam("stuff") String stuff) {
return stuff;
}
@GET
@Path("two/{stuff}")
public String getTwo(@PathParam("stuff") String stuff) {
return stuff;
}
}
public static void main(String[] args) throws Exception {
SelectorThread st = GrizzlyServerFactory.create("http://localhost:9999/");
try {
Client c = Client.create();
WebResource r = c.resource("http://localhost:9999/");
String s = r.get(String.class);
System.out.println(s);
} catch (UniformInterfaceException e) {
System.out.println(e.getResponse().getStatus());
e.printStackTrace();
} finally {
st.stopEndpoint();
System.exit(0);
}
}
}
Posted at 05:33PM Jun 27, 2008 by Paul Sandoz in REST | Comments[9]
@EJB injection
Jersey has a simple injection provider SPI for injecting instances for annotated fields, method/constructor parameters or setter methods. So it is possible to plug-in your own injection functionality.
Out of the box there is currently no EE-based functionality supported in Jersey but using the injection provider SPI it is very easy to have basic support for @EJB in one small class.
If you have the following resource:
@Path("foo")
public class FooResource {
@EJB private FooSessionRemote fooSessionRemoteBean;
@GET
@ProduceMime("text/plain")
public String get() throws Exception {
return fooSessionRemoteBean.fooMethod();
}
}
then the field fooSessionRemoteBean should get injected with an instance of the remote EJB interface.
The following provider class supports this behaviour:
@Provider
public class EJBProvider implements InjectableProvider<EJB, Type> {
public Scope getScope() {
return Scope.Singleton;
}
public Injectable getInjectable(ComponentContext cc, EJB ejb, Type t) {
if (!(t instanceof Class)) return null;
try {
Class c = (Class)t;
Context ic = new InitialContext();
final Object o = ic.lookup(c.getName());
return new Injectable<Object>() {
public Object getValue(HttpContext c) {
return o;
}
};
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
The EJB reference is looked up using JNDI then an Injectable instance is returned with that reference. This is efficient for per-request resources as the JNDI look up is only performed once. Since the above class is annotated with @Provider it will get picked up and treated like any other provider.
Obviously this could do with some polish to fully implement @EJB injection functionality but i think this example is instructive how one could support other annotations.
Posted at 02:16PM Jun 26, 2008 by Paul Sandoz in REST | Comments[19]
Jersey 0.8 is released
We have just released version 0.8 of Jersey (see the stable
download directory). This aligns with the 0.8 release of the JAX-RS
API
and the public review draft.
We made excellent progress in this time trial and we are releasing at least a week earlier than expected. This is good as it lets me show off 0.8 at Jazoon next week and lets us concentrate on the 0.9 etape over the summer period.
This version will be available soon from the Glassfish v2 and v3 update centers, and will be making it's way into NetBeans 6.5.
Thanks to the work of Jakub, Martin, Doug and others we are now pushing snapshot releases to here in the java.net maven 2 repository. This occurs automatically thanks to Hudson. Jakub shows how easy it is to use embedded Glassfish with Jersey from the maven 2 repository. The stable version has also been pushed, but as of writing there is an issue with the java.net maven repository infrastructure causing things to be delayed. When it appears we will send out another blog.
Martin has contributed Spring-based servlet support that is here in java.net maven 2 repository. This is great, now developers don't have to copy old code from mine and Marc's blog entries. Anybody willing to contribute support for Guice?
I refactored the container SPIs. Now it is much cleaner and easier, but more importantly it provides the basis for better Comet support and filtering that i hope to progress in 0.9. I also managed to unify the injection framework, make it more pluggable, and much more efficient for per-request resources.
It is a significant effort to transform a project from ant to maven and we are currently in an "interesting" transitional phase we hope to complete for the 0.9 release. As part of this we plan to split Jersey up into components as well as providing bundles, just like Grizzly does. So, hopefully, a developer can reduce the overall size of the jars required. For example, if a developer wants to use just the client API they are currently required to use the jar with all the unused server-side functionality. I believe this may also be advantageous for those wanting a smaller footprint for embedded servers.
After the successful Spring integration Martin is now working on a very interesting development combining JavaDoc doclets and WADL. The upshot of this work is that JavaDoc comments in resource classes will be pulled into the generated WADL document meaning that a developer does not have to separate documentation from the code of their RESTful Web services. See here for more details. I want to get this functionality merged into snapshot builds as soon as possible!
Posted at 05:38PM Jun 20, 2008 by Paul Sandoz in REST | Comments[6]