DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Curious about the future of data-driven systems? Join our Data Engineering roundtable and learn how to build scalable data platforms.

Data Engineering: The industry has come a long way from organizing unstructured data to adopting today's modern data pipelines. See how.

Threat Detection: Learn core practices for managing security risks and vulnerabilities in your organization — don't regret those threats!

Managing API integrations: Assess your use case and needs — plus learn patterns for the design, build, and maintenance of your integrations.

Avatar

Bill Burke

Joined Feb 2003

About

Bill Burke is an engineer and Fellow at Red Hat. He’s been a contributor, lead, and architect for numerous projects within the JBoss ecosystem for over 10 years, his current one being Resteasy, JBoss’s JAX-RS implementation. He has been Red Hat’s representative on the Java EE 5, EJB 3.0, JAX-RS 1.0 and 2.0 specifications. Bill is also the author of O’Reilly’s RESTful Java with JAX-RS and EnterpriseBeans 3.0. View his blog at bill.burkecentral.com

Stats

Reputation: 45
Pageviews: 399.5K
Articles: 3
Comments: 14
  • Articles
  • Comments

Articles

article thumbnail
RESTEasy 1.0 GA Released
This article was originally published on January 1, 2009. Java Just Got a Little Better Have you been struggling to use the Java system as it exists today? If so, don't worry, you are not alone. There are plenty of people going through the same troubles, and no one is pleased with the fact that they have to struggle as hard as they do just to get some simple code put out into the world. Unfortunately, that is the position that many find themselves in today. Java is finally starting to make some much-needed improvements, and people are clamoring to learn more about this service as they view it as a way to get their code out. The newest thing to come to Java that can add a lot of value for developers is RESTEasy 1.0. Easier to Transfer Creations to Apps There have been many complaints thrown at Java about how the data that is created within their system is not exactly easy to get transferred over to the apps that developers tend to want to put that data in. You can probably imagine how this could end up becoming a serious problem. Users are expecting the things that developers create to come out in app form these days, and if they are not provided with this accessibility, then they may be less than satisfied with the ultimate results that they get. Many people feel challenged to get their information and data over to apps so that customers will be pleased with the creations that they have come up with, and that is all fine and good, but it is not always easy to pull off in the Java platform. This is exactly why so many are excited to hear that RESTEasy 1.0 is on the way. RESTEasy 1.0 is literally living up to its name by giving users the chance to rest easily so that they will be able to get their data moved over to apps or anywhere else that they need it to go. There is no more waiting around wishing that you could get this done, it is now much more seamless than ever before. Integrates With Other Coding Tools We all know that some coding tools are built in such a way that they are separate from the other tools on the market. The creators of such tools sometimes think that it is a good idea to try to protect their intellectual property in this way. That may sound fine on paper, but the problem is that it makes their tools less valuable to users. They aren't able to use those same tools with the other coding tools that they are already using, and this can become a big issue for many developers. Needless to say, most people are not that into the idea of using coding tools that won't bring them the value that they have come to expect. As such, it makes sense that coders are now looking at what they can do to get their coding tools to better integrate with the other tools that they are already using. RESTEasy 1.0 is a great system because it doesn't try to shelter itself off in a corner somewhere. Instead, users are able to enjoy the full slate of benefits that this program can provide right from the start. You have many options when it comes to the tools that you use to code your various projects, and you don't want to limit yourself simply because some tools are not as responsive to your needs as others. You should always be able to work with the tools that you have at your disposal to get things done properly and right from the start. I am pleased to announce the first GA release of JBoss RESTEasy. All documentation and download links are available at RESTEasy's JBoss.org project page. JBoss RESTEasy is a framework that allows you to write RESTFul Web Services in Java. It is a fully certified and portable implementation of JAX-RS specification. JAX-RS is a new JCP specification that provides a Java API for RESTful Web Services over the HTTP protocol. RESTEasy can run in any Servlet container, but tighter integration with the JBoss Application Server is also available to make the user experience nicer in that environment. While JAX-RS is only a server-side specification, RESTEasy has innovated to bring JAX-RS to the client through the RESTEasy JAX-RS Client Framework. This client-side framework allows you to map outgoing HTTP requests to remote servers using JAX-RS annotations and interface proxies. Features Fully certified JAX-RS implementation Portable to any app-server/Tomcat that runs on JDK 5 or higher Embeddable server implementation for junit testing Rich set of providers for: XML, JSON, YAML, Fastinfoset, Atom, etc. JAXB marshalling into XML, JSON, Fastinfoset, and Atom as well as wrappers for arrays, lists, and sets of JAXB Objects. Asynchronous HTTP (Comet) abstractions for JBoss Web, Tomcat 6, and Servlet 3.0 EJB, Spring, and Spring MVC integration Client framework that leverages JAX-RS annotations so that you can write HTTP clients easily (JAX-RS only defines server bindings) Special thanks goes to all our independent contributors, specifically: Solomon Duskis, Ryan McDonough, Olivier Brand, Martin Algesten, Michael Brackx, and Justin Edelson. See also: Introduction to REST Putting Java to REST Enter The JBoss Matrix Constant Updates Another thing that needs to be celebrated about the release of RESTEasy 1.0 is the fact that it will be constantly updated and maintained behind the scenes. There are entire armies of engineers working to make sure this program stays up and running properly for its users at all times. This should give users confidence that they will be able to get everything they need out of it right when they need it. No more waiting around just hoping that your program will be updated. You know for sure that RESTEasy 1.0 has people working on it all the time. There are plenty of things that you can do to put yourself in a better position as far as the way you are coding and getting things taken care of. If you would like to, you can start working with the RESTEasy 1.0 system today to make sure you never again find yourself in a situation where you are dealing with potentially faulty coding software. This stuff is the best. Create Your Masterpiece One final note on RESTEasy 1.0 is the fact that you can get to work creating your masterpiece right away. You don't need to wait for anyone to give you permission to start getting work done. Instead, this user-friendly program is great for creating your next masterpiece in the coding world, and you should make sure you are taking full advantage of the opportunities that are presented to you in this way. Create a one-of-a-kind masterpiece that is top-notch and produces something that your users will never be able to forget. You can get started right now when you incorporate the RESTEasy 1.0 system into your next project. It is something that you need to get working for you right now. Make sure you take advantage of all that it can offer you today.
Updated July 24, 2022
· 22,479 Views · 2 Likes
article thumbnail
What's New in JAX-RS 2.0
JAX-RS is a framework designed to help you write RESTful applications both on the client and server side. With Java EE 7 is being slated to be released next year, 2013, JAX-RS is one of the specifications getting a deep revision. JAX-RS 2.0 is currently in the Public Draft phase at the JCP, so now is a good time to discuss some of the key new features so that you can start playing with your favorite JAX-RS implementation and give some valuable feedback the expert group needs to finalize the specification. Key features in 2.0: Client API Server-side Asynchronous HTTP Filters and Interceptors This article gives a brief overview of each of these features. Client Framework One huge thing missing from JAX-RS 1.0 was a client API. While it was easy to write a portable JAX-RS service, each JAX-RS implementation defined their own proprietary API. JAX-RS 2.0 fills in this gap with a fluent, low-level, request building API. Here's a simple example: Client client = ClientFactory.newClient(); WebTarget target = client.target("http://example.com/shop"); Form form = new Form().param("customer", "Bill") .param("product", "IPhone 5") .param("CC", "4444 4444 4444 4444"); Response response = target.request().post(Entity.form(form)); assert response.getStatus() == 200; Order order = response.readEntity(Order.class); Let's dissect this example code. The Client interface manages and configures HTTP connections. It is also a factory for WebTargets. WebTargets represent a specific URI. You build and execute requests from a WebTarget instance. Response is the same class defined in JAX-RS 1.0, but it has been expanded to support the client side. The example client, allocates an instance of a Client, creates a WebTarget, then posts form data to the URI represented by the WebTarget. The Response object is tested to see if the status is 200, then the application class Order is extracted from the response using the readEntity() method. The MessageBodyReader and MessageBodyWriter content handler interfaces defined in JAX-RS 1.0 are reused on the client side. When the readEntity() method is invoked in the example code, a MessageBodyReader is matched with the response's Content-Type and the Java type (Order) passed in as a parameter to the readEntity() method. If you are optimistic that your service will return a successful response, there are some nice helper methods that allow you to get the Java object directly without having to interact with and write additional code around a Response object. Customer cust = client.target("http://example.com/customers") .queryParam("name", "Bill Burke") .request().get(Customer.class); In this example we target a URI and specify an additional query parameter we want appended to the request URI. The get() method has an additional parameter of the Java type we want to unmarshal the HTTP response to. If the HTTP response code is something other than 200, OK, JAX-RS picks an exception that maps to the error code from a defined exception hierarchy in the JAX-RS client API. Asynchronous Client API The JAX-RS 2.0 client framework also supports an asynchronous API and a callback API. This allows you to execute HTTP requests in the background and either poll for a response or receive a callback when the request finishes. Future future = client.target("http://e.com/customers") .queryParam("name", "Bill Burke") .request() .async() .get(Customer.class); try { Customer cust = future.get(1, TimeUnit.MINUTES); } catch (TimeoutException ex) { System.err.println("timeout"); } The Future interface is a JDK interface that has been around since JDK 5.0. The above code executes an HTTP request in the background, then blocks for one minute while it waits for a response. You could also use the Future to poll to see if the request is finished or not. Here's an example of using a callback interface. InvocationCallback callback = new InvocationCallback { public void completed(Response res) { System.out.println("Request success!"); } public void failed(ClientException e) { System.out.println("Request failed!");n } }; client.target("http://example.com/customers") .queryParam("name", "Bill Burke") .request() .async() .get(callback); In this example, we instantiate an implementation of the InvocationCallback interface. We invoke a GET request in the background and register this callback instance with the request. The callback interface will output a message on whether the request executed successfully or not. Those are the main features of the client API. I suggest browsing the specification and Javadoc to learn more. Server-Side Asynchronous HTTP On the server-side, JAX-RS 2.0 provides support for asynchronous HTTP. Asynchronous HTTP is generally used to implement long-polling interfaces or server-side push. JAX-RS 2.0 support for Asynchronous HTTP is annotation driven and is very analogous with how the Servlet 3.0 specification handles asynchronous HTTP support through the AsyncContext interface. Here's an example of writing a crude chat program. @Path("/listener") public class ChatListener { List listeners = ...some global list...; @GET public void listen(@Suspended AsyncResponse res) { list.add(res); } } For those of you who have used the Servlet 3.0 asynchronous interfaces, the above code may look familiar to you. An AsyncResponse is injected into the JAX-RS resource method via the @Suspended annotation. This act disassociates the calling thread to the HTTP socket connection. The example code takes the AsyncResponse instance and adds it to a application-defined global List object. When the JAX-RS method returns, the JAX-RS runtime will do no response processing. A different thread will handle response processing. @Path("/speaker") public class ChatSpeaker { List listeners = ...some global list...; @POST @Consumes("text/plain") public void speak(String speech) { for (AsyncResponse res : listeners) { res.resume(Response.ok(speech, "text/plain").build());n } } } When a client posts text to this ChatSpeaker interface, the speak() method loops through the list of registered AsyncResponses and sends back an 200, OK response with the posted text. Those are the main features of the asynchronous HTTP interface, check out the Javadocs for a deeper detail. Filters and Entity Interceptors JAX-RS 2.0 has an interceptor API that allows framework developers to intercept request and response processing. This powerful API allows framework developers to transparently add orthogonal concerns like authentication, caching, and encoding without polluting application code. Prior to JAX-RS 2.0 many JAX-RS providers like Resteasy, Jersey, and Apache CXF wrote their own proprietary interceptor frameworks to deliver various features in their implementations. So, while JAX-RS 2.0 filters and interceptors can be a bit complex to understand please note that it is very use-case driven based on real-world examples. I wrote a blog on JAX-RS interceptor requirements awhile back to help guide the JAX-RS 2.0 JSR Expert Group on defining such an API. The blog is a bit dated, but hopefully you can get the gist of why we did what we did. JAX-RS 2.0 has two different concepts for interceptions: Filters and Entity Interceptors. Filters are mainly used to modify or process incoming and outgoing request headers or response headers. They execute before and after request and response processing. Entity Interceptors are concerned with marshaling and unmarshalling of HTTP message bodies. They wrap around the execution of MessageBodyReader and MessageBodyWriter instances. Server Side Filters On the server-side you have two different types of filters. ContainerRequestFilters run before your JAX-RS resource method is invoked. ContainerResponseFilters run after your JAX-RS resource method is invoked. As an added caveat, ContainerRequestFilters come in two flavors: pre-match and post-matching. Pre-matching ContainerRequestFilters are designated with the @PreMatching annotation and will execute before the JAX-RS resource method is matched with the incoming HTTP request. Pre-matching filters often are used to modify request attributes to change how it matches to a specific resource. For example, some firewalls do not allow PUT and/or DELETE invocations. To circumvent this limitation many applications tunnel the HTTP method through the HTTP header X-Http-Method-Override. A pre-matching ContainerRequestFilter could implement this behavior. @Provider public class HttpOverride implements ContainerRequestFilter { public void filter(ContainerRequestContext ctx) { String method = ctx.getHeaderString("X-Http-Method-Override"); if (method != null) ctx.setMethod(method); } } Post matching ContainerRequestFilters execute after the Java resource method has been matched. These filters can implement a range of features for example, annotation driven security protocols. After the resource class method is executed, JAX-RS will run all ContainerResponseFilters. These filters allow you to modify the outgoing response before it is marshalled and sent to the client. One example here is a filter that automatically sets a Cache-Control header. @Provider public class CacheControlFilter implements ContainerResponseFilter { public void filter(ContainerRequestContext req, ContainerResponseContext res) { if (req.getMethod().equals("GET")) { req.getHeaders().add("Cache-Control", cacheControl); } } } Client Side Filters On the client side you also have two types of filters: ClientRequestFilter and ClientResponseFilter. ClientRequestFilters run before your HTTP request is sent over the wire to the server. ClientResponseFilters run after a response is received from the server, but before the response body is unmarshalled. A good example of client request and response filters working together is a client-side cache that supports conditional GETs. The ClientRequestFilter would be responsible for setting the If-None-Match or If-Modified-Since headers if the requested URI is already cached. Here's what that code might look like. @Provider public class ConditionalGetFilter implements ClientRequestFilter { public void filter(ClientRequestContext req) { if (req.getMethod().equals("GET")) { CacheEntry entry = cache.getEntry(req.getURI()); if (entry != null) { req.getHeaders().putSngle("If-Modified-Since", entry.getLastModified()); } } } } The ClientResponseFilter would be responsible for either buffering and caching the response, or, if a 302, Not Modified response was sent back, to edit the Response object to change its status to 200, set the appropriate headers and buffer to the currently cached entry. This code would be a bit more complicated, so for brevity, we're not going to illustrate it within this article. Reader and Writer Interceptors While filters modify request or response headers, interceptors deal with message bodies. Interceptors are executed in the same call stack as their corresponding reader or writer. ReaderInterceptors wrap around the execution of MessageBodyReaders. WriterInterceptors wrap around the execution of MessageBodyWriters. They can be used to implement a specific content-encoding. They can be used to generate digital signatures or to post or pre-process a Java object model before or after it is marshalled. Here's an example of a GZIP encoding WriterInterceptor. @Provider public class GZIPEndoer implements WriterInterceptor { public void aroundWriteTo(WriterInterceptorContext ctx) throws IOException, WebApplicationException { GZIPOutputStream os = new GZIPOutputStream(ctx.getOutputStream()); try { ctx.setOutputStream(os); return ctx.proceed(); } finally { os.finish(); } } } Resource Method Filters and Interceptors Sometimes you want a filter or interceptor to only run for a specific resource method. You can do this in two different ways: register an implementation of DynamicFeature or use the @NameBinding annotation. The DynamicFeature interface is executed at deployment time for each resource method. You just use the Configurable interface to register the filters and interceptors you want for the specific resource method. @Provider public class ServerCachingFeature implements DynamicFeature { public void configure(ResourceInfo resourceInfo, Configurable configurable) { if (resourceInfo.getMethod().isAnnotationPresent(GET.class)) { configurable.register(ServerCacheFilter.class); } } } On the other hande, @NameBinding works a lot like CDI interceptors. You annotate a custom annotation with @NameBinding and then apply that custom annotation to your filter and resource method @NameBinding public @interface DoIt {} @DoIt public class MyFilter implements ContainerRequestFilter {...} @Path public class MyResource { @GET @DoIt public String get() {...} Wrapping Up Well, those are the main features of JAX-RS 2.0. There's also a bunch of minor features here and there, but youll have to explore them yourselves. If you want to testdrive JAX-RS 2.0 (and hopefully also give feedback to the expert group), Red Hat's Resteasy 3.0 and Oracle's Jersey project have implementations you can download and use. Useful Links Below are some useful links. I've also included links to some features in Resteasy that make use of filters and interceptors. This code might give you a more in-depth look into what you can do with this new JAX-RS 2.0 feature. JAX-RS 2.0 Public Draft Specification Resteasy 3.0 Download Jersey Resteasy 3.0 client cache implementation code (to see how filters interceptors work on client side) Doseta digital signature headers (good use case or interceptors) File suffix content negotiation implementation (server-side filter example) Other server-side examples (cache-control annotations, gzip encoding, role-based security)
November 1, 2012
· 90,031 Views · 3 Likes
article thumbnail
Introduction to REST
The bulk of my career has been spent working with and implementing distributed middleware. In the mid-90's I worked for the parent company of Open Environment Corporation working on DCE tools. Later on, I worked for Iona developing their next generation CORBA ORB. Currently, I work for the JBoss division of Red Hat, which is entrenched in Java middleware. So, you could say that I have a pretty rich perspective when it comes to middleware. Over a year ago, I became exposed to a new way of writing Web Services called REST. REST is about using the principles of the World Wide Web to build applications. REST stands for REpresentational State Transfer and was first defined within a PhD thesis by Roy Fielding. REST is a set of architectural principles which ask the following questions: Why is the World Wide Web so prevalent and ubiquitous? What makes the Web scale? How can I apply the architecture of the Web to my own applications? While REST has many similarities to the more traditional ways of writing SOA applications, in many important ways it is very different. You would think that my background would be an asset to understanding this new way of creating web services, but unfortunately this was not the case. The reason is that some of the concepts of REST are hard to swallow, especially if you have written successful SOAP or CORBA applications. If your career has a foundation in one of these older technologies, there's a bit of emotional baggage you will have to overcome. For me, it took a few months and a lot of reading. For you, it may be easier. For others, they will never pick REST over something like SOAP and WS-*. I just ask that you keep an open mind and do some research if I fail to convince you that REST is an intriguing alternative to WS-*. So... RESTful Architectural Principles REST isn't protocol specific, but when people talk about REST they usually mean REST over HTTP. Technologies like SOAP use HTTP strictly as a transport protocol and thus use a very small subset of its capabilities. Many would say that WS-* uses HTTP solely to tunnel through firewalls. HTTP is actually a very rich application protocol which gives us things like content negotiation and distributed caching. RESTful web services try to leverage HTTP in its entirety using specific architectural principles. What are those RESTful principles? Addressable Resources. Every “thing” on your network should have an ID. With REST over HTTP, every object will have its own specific URI. A Uniform, Constrained Interface. When applying REST over HTTP, stick to the methods provided by the protocol. This means following the meaning of GET, POST, PUT, and DELETE religiously. Representation oriented. You interact with services using representations of that service. An object referenced by one URI can have different formats available. Different platforms need different formats. AJAX may need JSON. A Java application may need XML. Communicate statelessly. Stateless applications are easier to scale. Let's go into more detail on each of these individual principles. Addressability Addressability is the idea that every object and resource in your system is reachable through a unique identifier. This seems like a no-brainer, but, if you think about it, standardized object identity isn't available in many environments. If you have tried to implement a portable J2EE application you probably know what I mean. In J2EE, distributed and even local references to services are not standardized so it make portability really difficult. This isn't such a big deal for one application, but with the new popularity of SOA, we're heading to a world where disparate applications must integrate and interact. Not having something as simple as service addressability standardized adds a whole complex dimension to integration efforts. In the REST world, addressability is addressed through the use of URIs. URIs are standardized and well-known. Anybody who has ever used a browser is familiar with URIs. From a URI we know the object's protocol. In other words, we know how to communicate with the object. We know its host and port or rather, where it is on the network. Finally, we know the resource's path on its host, which is its identity on the server it resides. Using a unique URI to identify each of your services make each of your resources linkable. Service references can be embedded in documents or even emails. For instance, consider the situation where somebody calls your company's help desk with a problem with your SOA application. They can email a link to the developers on what exact service there was problems with. Furthermore, the data which services publish can also be composed into larger data streams fairly easily. Figure 1-1 http://customers.myintranet.com/customers/32133 5 http://products.myintranet.com/products/111 ... In this example, we have an XML document that describes a e-commerce order entry. We can reference data provided by different divisions in a company. From this reference we can not only obtain information about the linked customer and products that were bought, but we also have the identifier of the service this data comes from. We know exactly where we can further interact and manipulate this data if we so desired. The Uniform, Constrained Interface The REST principle of a constrained interface is perhaps the hardest pill for an experienced CORBA or SOAP developer to swallow. The idea behind it is that you stick to the finite set of operations of the application protocol you're distributing your services upon. For HTTP, this means that services are restricted to using the methods GET, PUT, DELETE, and POST. Let's explain each of these methods: GET is a read only operation. It is both an idempotent and safe operation. Idempotent means that no matter how many times you apply the operation, the result is always the same. The act of reading an HTML document shouldn't change the document. Safe means that invoking a GET does not change the state of the server at all. That, other than request load, the operation will not affect the server. PUT is usually modeled as an insert or update. It is also idempotent. When using PUT, the client knows the identity of the resource it is creating or updating. It is idempotent because sending the same PUT message more than once has no affect on the underlying service. An analogy is an MS Word document that you are editing. No matter how many times you click the “save” button, the file that stores your document will logically be the same document. DELETE is used to remove services. It is idempotent as well. POST is the only non-idempotent and unsafe operation of HTTP. It is a method where the constraints are relaxed to give some flexibility to the user. In a RESTFul system, POST usually models a factory service. Where with PUT you know exactly which object you are creating, with POST you are relying on a factory service to create the object for you. You may be scratching your head and thinking, “How is it possible to write a distributed service with only 4 methods?” Well... SQL only has 4 operations: SELECT, INSERT, UPDATE, and DELETE. JMS and other MOMs really only have two: send and receive. How powerful are both of these tools? For both SQL and JMS, the complexity of the interaction is confined purely to the data model. The addressability and operations are well defined and finite and the hard stuff is delegated to the data model (in SQL's case) or the message body(JMS's case). Why is the Uniform Interface Important? Constraining the interface for your web services has many more advantages than disadvantages. Let's look at a few: Familiarity If you have a URI that points to a service you know exactly what methods are available on that resource. You don't need a IDL-like file describing what methods are available. You don't need stubs. All you need is an HTTP client library. If you have a document that is composed of links to data provided by many different services, you already know what method to call to pull in data from those links. Interoperability HTTP is a very ubiquitous protocol. Most programming languages have an HTTP client library available to them. So, if your web service is exposed via REST, there is a very high probably that people that want to use your service will be able to without any additional requirements beyond being able to exchange the data formats the service is expecting. With CORBA or WS-* you have to install vendor specific client libraries. How many of you have had the problem of getting CORBA or WS-* vendors to interoperate? It has traditionally been very problematic. The WS-* set of specifications have also been a moving target over the years. So with WS-* and CORBA, you not only have to worry about vendor interoperability, you have to make sure that your client and server are using the same specification version. With REST over HTTP, you don't have to worry about either of these things and can just focus on understanding the data format of the service. I like to think that you are focusing on what is really important: application interoperability, rather than vendor interoperability. Scalability Because REST constrains you to a well-defined set of methods, you have predictable behavior which can have incredible performance benefits. GET is the strongest example. Because GET is a read method that is both idempotent and safe, browsers and HTTP proxies can cache responses to servers which can save a huge amount of network traffic and hits to your website. Add the capabilities of HTTP 1.1's Cache-Control header, and you have a incredibly rich way of defining caching policies for your services. It doesn't end with caching though. Consider both PUT and DELETE. Because they are idempotent, the client, nor the server have to worry about handling duplicate message delivery. This saves a lot of book keeping and complex code. Representation Oriented The third architectural principle of REST is that your services should be representation oriented. Each service is addressable through a specific URI and representations are exchanged between the client and service. With a GET operation you are receiving a representation of the current state of that resource. A PUT or POST passes a representation of the resource to the server so that the underlying resource's state can change. In a RESTful system, the complexity of the client-server interaction is within the representations being passed back and forth. These representations could be XML, JSON, YAML, or really any format you can come up with. One really cool thing about HTTP is that it provides a simple content negotiation protocol between the client and server. Through the Content-Type header, the client specifies the representation's type. With the Accept header, the client can list its preferred response formats. AJAX clients can ask for JSON, Java for XML, Ruby for YAML. Another thing this is very useful for is versioning of services. The same service can be available through the same URI with the same methods (GET, POST, etc.), and all that changes is the mime type. For example, the mime type could be “application/xml” for an old service while newer services could exchange “application/xml;schemaVersion=1.1” mime types. All and all, because REST and HTTP have a layered approach to addressability, method choice, and data format, you have a much more decoupled protocol that allows your service to interact with a wide variety of different clients in a consistent way. Communicate Statelessly The last RESTful principle I will discuss is the idea of statelessness. When I talk about statelessness though, I don't mean that your applications can't have state. In REST, stateless means that there is no client session data stored on the server. The server only records and manages the state of the resources it exposes. If there needs to be session specific data, it should be held and maintained by the client and transfered to the server with each request as needed. A service layer that does not have to maintain client sessions is a lot easier to scale as it has to do a lot less expensive replications in a clustered environment. Its a lot easier to scale up as all you have to do is add machines. A world without server maintained session data isn't so hard to imagine if you look back 12-15 years ago. Back then many distributed applications had a fat GUI client written in Visual Basic, Power Builder, or Visual C++ talking RPCs to a middle-tier that sat in front of a database. The server was stateless and just processed data. The fat client held all session state. The problem with this architecture was an operations one. It was very hard for operations to upgrade, patch, and maintain client GUIs in large environments. Web applications solved this problem because the applications could be delivered from a central server and rendered by the browser. We started maintaining client sessions on the server because of the limitations of the browser. Now, circa 2008, with the growing popularity of AJAX, Flex, and Java FX, the browsers are sophisticated enough to maintain their own session state like their fat-client counterparts in the mid-90s used to do. We can now go back to that stateless scalable middle tier that we enjoyed in the past. Its funny how things go full circle sometimes. Conclusion REST identifies the key architectural principles of why the World Wide Web is so prevalent and scalable. The next step in the evolution of the web is to apply these principles to the semantic web and the world of web services. REST offers a simple, interoperable, and flexible way of writing web services that can be very different than the RPC mechanisms like CORBA and WS-* that so many of us have had training in. This article is the first of a two part series. In this article I wanted to introduce you to the basic concepts of REST. In my next article “Putting Java to REST”, we will build a very simple RESTful service in Java using the new JCP standard JAX-RS. In other words, you'll get to see the theory being put into action. Until then, I urge you to read more about REST. Below are some interesting links. Read Part II of this series: Putting Java to REST Links O'Reilly's "RESTful Web Services" book Addressing Doubts about REST The REST WIKI About the Author Bill Burke is an engineer and Fellow at the JBoss division of Red Hat. He blogs regularly at bill.burkecentral.com.
August 18, 2008
· 84,926 Views · 12 Likes

Comments

What's New in JAX-RS 2.0

Nov 02, 2012 · Bill Burke

JAX-RS is stream based. All the MessageBodyReader/Writer's use streams. JAXB, I think, pretty much requires streams. Jackson? not sure.

Non-blocking interfaces might be an interesting thing to look at in JAX-RS 3.0.

What's New in JAX-RS 2.0

Nov 02, 2012 · Bill Burke

JAX-RS is stream based. All the MessageBodyReader/Writer's use streams. JAXB, I think, pretty much requires streams. Jackson? not sure.

Non-blocking interfaces might be an interesting thing to look at in JAX-RS 3.0.

What's New in JAX-RS 2.0

Nov 02, 2012 · Bill Burke

JAX-RS is stream based. All the MessageBodyReader/Writer's use streams. JAXB, I think, pretty much requires streams. Jackson? not sure.

Non-blocking interfaces might be an interesting thing to look at in JAX-RS 3.0.

RIP…JDK 1.4

Nov 02, 2012 · Alex Miller

JAX-RS is stream based. All the MessageBodyReader/Writer's use streams. JAXB, I think, pretty much requires streams. Jackson? not sure.

Non-blocking interfaces might be an interesting thing to look at in JAX-RS 3.0.

RIP…JDK 1.4

Nov 02, 2012 · Alex Miller

JAX-RS is stream based. All the MessageBodyReader/Writer's use streams. JAXB, I think, pretty much requires streams. Jackson? not sure.

Non-blocking interfaces might be an interesting thing to look at in JAX-RS 3.0.

RIP…JDK 1.4

Nov 02, 2012 · Alex Miller

JAX-RS is stream based. All the MessageBodyReader/Writer's use streams. JAXB, I think, pretty much requires streams. Jackson? not sure.

Non-blocking interfaces might be an interesting thing to look at in JAX-RS 3.0.

Struts Custom Validators

Oct 06, 2008 · Lebon Bon Lebon

Basic Auth does not require human interaction. I agree it is not sophisticated, but combine it with SSL and its fine. I could not get DIGEST to work with Tomcat. I don't think it supports CLIENT-CERT. You could use form based security and pass the session cookie around too I guess. But, IMO, basic auth is as secure as form based security.

AFAIK, there is no portable way to define a custom authentication mechanism. Yes, you could write a filter to process custom headers, but there would be no way to associate user identity with the HttpServletRequest.

Struts Custom Validators

Oct 06, 2008 · Lebon Bon Lebon

I don't know about Apache CXF, but RESTEasy and Jersey are implemented as a servlet. Since they are implemented as a servlet, you use web.xml security constraints to set up authentication. Authorization (role-based-security) is a bit trickier as the servlet spec has *very* limited url-pattern expressions. In this case you could use either EJBs, Spring, or some other component model that has a security infrastructure, to do your fine-grain security.

For your second question, @Path is limited to whatever Java annotations support. So I don't think your particular example would work.

Your third question, how can you handle exceptions thrown by the JAX-RS service? Well, I did talk about ExceptionHandlers. Beyond that, there really is no standard way to errors on the server. Errors do usually have a HTTP mapped resposne. For example, a bad representation sent to the server might get a status code of 400 or 406. If the server doesn't support a particular http method, 405 would be returned with an Allow header, etc. In your example, the client would receive a status code of 404 NOT FOUND. All this stuff is standard HTTP. I suggest reading the HTTP 1.1 specification. It really is an easy read.

JAX-RS Vendor Comparisons

Sep 28, 2008 · Solomon Duskis

RESTEasy is not just a playground for new ideas. We're actually going to be supporting it within JBoss very soon (as soon as I can get my hands on the TCK!) and have a number of large customers who already use RESTEasy breathing down our necks to do so.

We're also going to be delivering on a few ideas that distinguish us greatly from the other projects:

* a client annotation-based framework (already exists)

* An asynchronous job facility

* Asynchronous HTTP support

* Client and server side caching

* HATEOAS capablities

On another note, it would be cool to get some unbiased opinion comparing a pure JAX-RS approach to something thats heavily engineered like RESTlet or something more simple like vanilla servlets.

SOA = Snake Oil-oriented Architecture?

Sep 28, 2008 · Peter Stofferis

RESTEasy is not just a playground for new ideas. We're actually going to be supporting it within JBoss very soon (as soon as I can get my hands on the TCK!) and have a number of large customers who already use RESTEasy breathing down our necks to do so.

We're also going to be delivering on a few ideas that distinguish us greatly from the other projects:

* a client annotation-based framework (already exists)

* An asynchronous job facility

* Asynchronous HTTP support

* Client and server side caching

* HATEOAS capablities

On another note, it would be cool to get some unbiased opinion comparing a pure JAX-RS approach to something thats heavily engineered like RESTlet or something more simple like vanilla servlets.

Python 2.4.4 (Final)

Sep 23, 2008 · Erik Thauvin

Hey Jacek, just wondering... What "attitude" did you get from JBoss that made you switch? We still deliver community versions/updates for free on all our projects. Thanks.
Python 2.4.4 (Final)

Sep 23, 2008 · Erik Thauvin

Hey Jacek, just wondering... What "attitude" did you get from JBoss that made you switch? We still deliver community versions/updates for free on all our projects. Thanks.
Python 2.4.4 (Final)

Sep 23, 2008 · Erik Thauvin

Hey Jacek, just wondering... What "attitude" did you get from JBoss that made you switch? We still deliver community versions/updates for free on all our projects. Thanks.
Introduction to REST

Aug 19, 2008 · Bill Burke

IMO, most of what WSDL describes is built into REST and not needed. With REST there's no need to describe the methods as you already know what they are and how they behave. You would still need to human document your resources (as you would with WSDL). With WSDL you still need an external document (an XSD) to define the data format (and you are limited to XML).

There's WADL, but I think something like this document is easier to read.

User has been successfully modified

Failed to modify user

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: