
|
![]()
|
From the Blogosphere Java Web Services Tutorial | @CloudExpo #DevOps #API #Java #Microservices
Web services have taken the development world by storm
By: Stackify Blog
Aug. 30, 2017 02:30 AM
Web services have taken the development world by storm, especially in recent years as they've become more and more widely adopted. There are naturally many reasons for this, but first, let's understand what exactly a web service is. The World Wide Web Consortium (W3C) defines "web of services" as "message-based design frequently found on the Web and in enterprise software". Basically, a web service is a method of sending a message between two devices through a network. In practical terms, this translates to an application which outputs communication in a standardized format for other client applications to receive and act on. Web services have been adopted so quickly because they bring several important advantages:
Historically, there are two primary types of web services: SOAP (Simple Object Access Protocol) and REST (REpresentational State Transfer) services; the latter is more recent and more widely used today. This article will detail both, but put a stronger focus on REST. Differences between SOAP and REST web services One of the advantages of SOAP is that it supports multiple protocols, has built-in security and error handling, and is somewhat strictly regulated, which can lead to a higher level of standardization. However, SOAP is also fairly difficult to use and requires significant resources, which excludes it as an option on some embedded or mobile devices. By contrast, REST is lighter, faster, more flexible and, as such, easier to use. It can also output data in several formats including XML and JSON. Here's a simple, high-level summary of the main differences between the two standards: You can read more about the differences between the two architectural approaches here. SOAP Web Services In the Java ecosystem, Java EE provides the JAX-WS API to help you create SOAP-based web services. With JAX-WS, you can define a SOAP service in both an RPC or Document style. Both styles consist of a set of annotations to be applied to your classes, based on which the XML files are generated. Let's see an example of an RPC style web service. First, you need to create an interface or class with the proper annotations, which will declare the methods to be accessed by other applications:
We used two primary annotations here - @WebService to declare the service interface, and @WebMethod for each method to be exposed. The @SoapBinding annotation specifies the style of web service. A Document-style service is declared in a similar manner, replacing the @SoapBinding annotation with:
The difference between the two styles is in the way the XML files are generated. Finally, you need to add an implementation class for the service interface:
The implementing methods must be public, and must not be static or final. You can also make use of methods annotated with @PostConstruct and @PreDestroy for lifecycle event callbacks. Note that creating the interface is optional for a JAX-WS web service implementation. You can add the annotations directly to the class, and JAX-WS will implicitly define a service endpoint interface. Finally, to publish the web service, use the Endpoint class:
If you run this application, you can see the XML describing your endpoint, written in WSDL (Web Service Description Language) format, by accessing the URL:
SOAP Web Service Client One way to do this is by creating a Java project and importing the web service definitions from the web service WSDL document. After creating the project, open a command line and move to the source folder of the new project; then execute the command:
This will have the effect of generating the following classes in your source folder: Now, you can easily make use of the generated classes:
REST Web Services In a few short years, REST has overtaken SOAP in popularity due to its ease of use, speed, flexibility, and similarity to core architecture choices that power the web itself. Here's an interesting graph that shows the popularity of both approaches in the Java ecosystem: Let's have a quick look at the core principles of a REST API:
REST With JAX-RS JAX-RS Annotations and Setup In the example, we're going to use the reference implementation of JAX-RS, which is Jersey; another very popular implementation you can try is RESTEasy. Let's start by first understanding the most important annotations in JAX-RS:
The API also contains annotations corresponding to each HTTP verb: @GET, @POST, @PUT, @DELETE, @HEAD, @OPTIONS. To start working with the Jersey JAX-RS implementation, you need to add the jersey-server dependency to your project classpath. If you're using Maven, this is easily done and will also bring in the required jsr311-api dependency:
In addition to this, you can also add the jersey-media-moxy library to enable the API to enable JSON representations:
Having the option to use JSON as the primary representation media type can be quite powerful, not only for flexibility but also in terms of performance. The JAX-RS Web Service
Notice how we're creating two endpoints here - a /users POST endpoint for adding a User resources, and a /users GET endpoint for retrieving the list of users. Next, you need to define the configuration - extending ResourceConfig and specifying the packages to be scanned for JAX-RS services:
Finally, you need to add a web.xml file which registers the ServletContainer servlet and the ApplicationInitializer class:
After running the application, you can access the endpoints at http://localhost:8080/rest-server/users. Using curl, you can add a new user:
Then retrieve the collection resource using a simple GET:
Testing the REST Web Service That's exactly what we're going to do here - use a powerful client specifically focused on testing REST services - REST Assured:
REST Assured follows a typical BDD format, with each statement structured like this:
Let's take a look at a simple JUnit test for the REST service we developed previously:
In this quick test, we send a POST to the /users endpoint to create a new User. Then, we do a GET, retrieve all users and verify the response to check if it contains the new user we just created. Of course, to run the test, you first need to make sure the API is running on localhost first. Building a Client for the REST Service Let's use Angular 4 to create a simple front-end client, with an HTML form to add a user and a table to display all users in the system. Angular 4 is quite well-suited as a front-end framework for working with REST services - as it has first-class REST support with the Http module. To start using the library, you first need to install node.js and npm, then download the Angular command line interface:
To setup a new Angular project, navigate to your project location and run:
The process of setting up the project can take a few minutes. At the end, a number of new files will be created. In the src/app folder, let's create an app.service.ts file where a User class will be defined, as well as UserService which calls the two web services endpoints:
Next, let's create an Angular Component that will make use of the UserService and create objects to bind to HTML elements:
The visual interface of the Angular application contains an HTML form and table, with data bindings:
Let's define the main AppComponent that will include the UsersComponent:
This is all wrapped up in the main application module:
Finally, the UsersComponent is included in the main HTML page:
To run the Angular application, go to the project directory in a command line, and simply run the command:
The application can be accessed at the URL: http://localhost:4200/ Since the REST client and server run on different origins, by default the Angular client cannot access the REST endpoints, due to the CORS constraint in the browser. In order to allow cross-origin requests, let's add a filter to the REST web service application that adds an Access-Control-Allow-Origin header to every response:
Finally, you will be able to communicate with the REST web service from the Angular application. REST Services with Spring Simply put, Spring MVC offers a similar programming model, driven by the @RestController and @RequestMapping annotations, to expose the API to clients. A good way to start bootstrapping a Spring application is making use of Spring Boot:
After adding the necessary dependencies, you can create a @RestController annotated class with methods for each web service endpoint. The example will be the same as the previous one - handing User resources - to better illustrate the differences and similarities between the two approaches:
With Spring, you have similar handy annotations, corresponding to each HTTP method, such as @PostMapping and @GetMapping. You can define the endpoint URL using the value attribute, or specify the media type consumed or produced by the service by using the consumes or produces attributes. Of course, the REST support in Spring goes far beyond these simple operations and provides a full programming model to build APIs. If you'd like to go deeper into what's possible, have a look at the reference documentation here. Best Practices for REST Services One of the most important principles to follow when building your REST service is the HATEOAS constraint. HATEOAS stands for "Hypermedia as the Engine of Application State" and states that a client should be able to interact with a web service, by only using the hypermedia information provided by the service itself. The main purpose of HATEOAS is to decouple client and server functionality so that changes to the service do not break client functionality, and the service can evolve independently of clients. Simply put, in addition to the standard responses, a service implementing HATEOAS will also include links to provide the client with a set of available operations they can perform with the API. Both JAX-RS and Spring provide support for building HATEOAS services. Spring REST HATEOAS Support First, you need to add the spring-boot-starter-hateoas dependency:
Next, you have to modify the resource class User so that it extends the ResourceSupport class:
Then you can modify the REST controller to add a link. Spring HATEOAS contains the Link class and helpful methods to obtain the URIs:
This simple implementation adds a Link to each User resource - pointing the client to the canonical URI of the resource - /users/{email}. Once you expose that URI, you of course also have to define a method to handle that endpoint mapping as well:
Calling the /users endpoint will now return an enriched Resource:
The standardization work in the REST ecosystem is making slow but steady progress; however, we're not yet at a point where documentation of the API isn't necessary. Right now, documentation is actually very helpful and makes exploring and understanding the API a lot easier; that's why tools like Swagger and RAML have gained so much traction in recent years. Documenting the API with Swagger Swagger is a specification that can be integrated with JAX-RS implementations, as well as with Spring REST implementations. Let's set up Swagger in the simple Spring REST API we created, and have a look at the generated documentation. First, you'll need the springfox-swagger2 dependency, as well as springfox-swagger-ui if you want a visual interface:
In Spring Boot, the configuration only requires defining a Docket bean and adding the @EnableSwagger2 annotation:
This is all that is needed to support Swagger documentation generation for your Spring REST API in a Spring Boot application. Then you can access the documentation at /swagger-ui.html: Notice how the each endpoint in the application is individually documented; you can expand each section to find details about the endpoint and even interact with it right from the Swagger UI. Conclusion Naturally, there are several mature frameworks available to implement both REST and SOAP services in the Java ecosystem. And beyond the server side, there's solid support to test and document web services running over HTTP. And, of course, the upcoming first-class Spring support for reactive architectures promises to keep this momentum strong and to address some of the limitations of the HTTP protocol, leading to even more performant APIs. The post Java Web Services Tutorial: Improve App Communication And Flexibility appeared first on Stackify. Download Show Prospectus ▸ Here DevOps at Cloud Expo taking place October 31 - November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA, will feature technical sessions from a rock star conference faculty and the leading industry players in the world. Must Watch Video: Recap of @DevOpsSummit New York Javits Center The widespread success of cloud computing is driving the DevOps revolution in enterprise IT. Now as never before, development teams must communicate and collaborate in a dynamic, 24/7/365 environment. There is no time to wait for long development cycles that produce software that is obsolete at launch. DevOps may be disruptive, but it is essential. Nutanix DevOps Booth at @DevOpsSummit New York Javits Center DevOps at Cloud Expo will expand the DevOps community, enable a wide sharing of knowledge, and educate delegates and technology providers alike. Recent research has shown that DevOps dramatically reduces development time, the amount of enterprise IT professionals put out fires, and support time generally. Time spent on infrastructure development is significantly increased, and DevOps practitioners report more software releases and higher quality. Sponsors of DevOps at Cloud Expo will benefit from unmatched branding, profile building and lead generation opportunities through:
For more information on sponsorship, exhibit, and keynote opportunities, contact Carmen Gonzalez by email at events (at) sys-con.com, or by phone 201 802-3021. Most Popular Video: Sheng Liang's Containers Talk @DevOpsSummit at Cloud Expo taking place October 31 - November 2, 2017, Santa Clara Convention Center, CA, and is co-located with the 21st International Cloud Expo and will feature technical sessions from a rock star conference faculty and the leading industry players in the world. @DevOpsSummit 2017 Silicon Valley @DevOpsSummit 2018 New York With major technology companies and startups seriously embracing Cloud strategies, now is the perfect time to attend 21st Cloud Expo, October 31 - November 2, 2017, at the Santa Clara Convention Center, CA, and June 12-14, 2018, at the Javits Center in New York City, NY, and learn what is going on, contribute to the discussions, and ensure that your enterprise is on the right path to Digital Transformation. Track 1. Enterprise Cloud | Cloud-Native Speaking Opportunities The upcoming 21st International @CloudExpo | @ThingsExpo, October 31 - November 2, 2017, Santa Clara Convention Center, CA, and June 12-14, 2018, at the Javits Center in New York City, NY announces that its Call For Papers for speaking opportunities is open. Themes and topics to be discussed include:
Submit your speaking proposal today! ▸ Here Cloud Expo | @ThingsExpo 2017 Silicon Valley Cloud Expo | @ThingsExpo 2018 New York Download Show Prospectus ▸ Here Every Global 2000 enterprise in the world is now integrating cloud computing in some form into its IT development and operations. Midsize and small businesses are also migrating to the cloud in increasing numbers. Cloud Expo is the single show where technology buyers and vendors can meet to experience and discus cloud computing and all that it entails. Sponsors of Cloud Expo will benefit from unmatched branding, profile building and lead generation opportunities through:
For more information on sponsorship, exhibit, and keynote opportunities, contact Carmen Gonzalez by email at events (at) sys-con.com, or by phone 201 802-3021. The World's Largest "Cloud Digital Transformation" Event @CloudExpo | @ThingsExpo 2017 Silicon Valley @CloudExpo | @ThingsExpo 2018 New York Full Conference Registration Gold Pass and Exhibit Hall ▸ Here Register For @CloudExpo ▸ Here via EventBrite Register For @ThingsExpo ▸ Here via EventBrite Register For @DevOpsSummit ▸ Here via EventBrite Sponsorship Opportunities Sponsors of Cloud Expo | @ThingsExpo will benefit from unmatched branding, profile building and lead generation opportunities through:
For more information on sponsorship, exhibit, and keynote opportunities, contact Carmen Gonzalez (@GonzalezCarmen) today by email at events (at) sys-con.com, or by phone 201 802-3021. Secrets of Sponsors and Exhibitors ▸ Here All major researchers estimate there will be tens of billions devices - computers, smartphones, tablets, and sensors - connected to the Internet by 2020. This number will continue to grow at a rapid pace for the next several decades. With major technology companies and startups seriously embracing Cloud strategies, now is the perfect time to attend @CloudExpo | @ThingsExpo, October 31 - November 2, 2017, at the Santa Clara Convention Center, CA, and June 12-4, 2018, at the Javits Center in New York City, NY, and learn what is going on, contribute to the discussions, and ensure that your enterprise is on the right path to Digital Transformation. Delegates to Cloud Expo | @ThingsExpo will be able to attend 8 simultaneous, information-packed education tracks. There are over 120 breakout sessions in all, with Keynotes, General Sessions, and Power Panels adding to three days of incredibly rich presentations and content. Join Cloud Expo | @ThingsExpo conference chair Roger Strukhoff (@IoT2040), October 31 - November 2, 2017, Santa Clara Convention Center, CA, and June 12-14, 2018, at the Javits Center in New York City, NY, for three days of intense Enterprise Cloud and 'Digital Transformation' discussion and focus, including Big Data's indispensable role in IoT, Smart Grids and (IIoT) Industrial Internet of Things, Wearables and Consumer IoT, as well as (new) Digital Transformation in Vertical Markets. Financial Technology - or FinTech - Is Now Part of the @CloudExpo Program! Accordingly, attendees at the upcoming 21st Cloud Expo | @ThingsExpo October 31 - November 2, 2017, Santa Clara Convention Center, CA, and June 12-14, 2018, at the Javits Center in New York City, NY, will find fresh new content in a new track called FinTech, which will incorporate machine learning, artificial intelligence, deep learning, and blockchain into one track. Financial enterprises in New York City, London, Singapore, and other world financial capitals are embracing a new generation of smart, automated FinTech that eliminates many cumbersome, slow, and expensive intermediate processes from their businesses. FinTech brings efficiency as well as the ability to deliver new services and a much improved customer experience throughout the global financial services industry. FinTech is a natural fit with cloud computing, as new services are quickly developed, deployed, and scaled on public, private, and hybrid clouds. More than US$20 billion in venture capital is being invested in FinTech this year. @CloudExpo is pleased to bring you the latest FinTech developments as an integral part of our program, starting at the 21st International Cloud Expo October 31 - November 2, 2017 in Silicon Valley, and June 12-14, 2018, in New York City. @CloudExpo is accepting submissions for this new track, so please visit www.CloudComputingExpo.com for the latest information. About SYS-CON Media & Events SYS-CON Media (www.sys-con.com) has since 1994 been connecting technology companies and customers through a comprehensive content stream - featuring over forty focused subject areas, from Cloud Computing to Web Security - interwoven with market-leading full-scale conferences produced by SYS-CON Events. The company's internationally recognized brands include among others Cloud Expo® (@CloudExpo), Big Data Expo® (@BigDataExpo), DevOps Summit (@DevOpsSummit), @ThingsExpo® (@ThingsExpo), Containers Expo (@ContainersExpo) and Microservices Expo (@MicroservicesE). Cloud Expo®, Big Data Expo® and @ThingsExpo® are registered trademarks of Cloud Expo, Inc., a SYS-CON Events company. Presentation Slides
@CloudExpo Stories
|
![]()
Tweets by @BigDataExpo ![]()
![]() ![]()
![]()
![]()
![]() @CloudExpo Blogs
|