React.js and Spring Data REST: Part 4 - Events

Engineering | Greg L. Turnquist | October 13, 2015 | ...
To see updates to this code, visit our React.js and Spring Data REST tutorial.

In the previous session, you introduced conditional updates to avoid collisions with other users when editing the same data. You also learned how to version data on the backend with optimistic locking. You got a tip off if someone edited the same record so you could refresh the page and get the update.

That’s good. But do you know what’s even better? Having the UI dynamically respond when other people update the resources.

In this session you’ll learn how to use Spring Data REST’s built in event system to detect changes in the backend and publish updates to ALL users through Spring’s WebSocket support. Then you’ll be able to dynamically adjust clients as the data updates.

Feel free to grab the code from this repository and follow along. This session is based on the previous session’s app with extra things added.

Adding Spring WebSocket support to the project

Before getting underway, you need to add a dependency to your project’s pom.xml file:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-websocket</artifactId>
</dependency>

This bring in Spring Boot’s WebSocket starter.

Configuring WebSockets with Spring

Spring comes with powerful WebSocket support. One thing to recognize is that a WebSocket is a very low level protocol. It does little more than offer the means to transmit data between client and server. The recommendation is to use a sub-protocol (STOMP for this session) to actually encode data and routes.

The follow code is used to configure WebSocket support on the server side:

@Component
@EnableWebSocketMessageBroker
public class WebSocketConfiguration extends AbstractWebSocketMessageBrokerConfigurer {
static final String MESSAGE_PREFIX = "/topic";

@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
	registry.addEndpoint("/payroll").withSockJS();
}

@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
	registry.enableSimpleBroker(MESSAGE_PREFIX);
	registry.setApplicationDestinationPrefixes("/app");
}

}

  • @EnableWebSocketMessageBroker turns on WebSocket support.
  • AbstractWebSocketMessageBrokerConfigurer provides a convenient base class to configure basic features.
  • MESSAGE_PREFIX is the prefix you will prepend to every message’s route.
  • registerStompEndpoints() is used to configure the endpoint on the backend for clients and server to link (/payroll).
  • configureMessageBroker() is used to configure the broker used to relay messages between server and client.

With this configuration, it’s now possible to tap into Spring Data REST events and publish them over a WebSocket.

Subscribing to Spring Data REST events

Spring Data REST generates several application events based on actions occurring on the repositories. The follow code shows how to subscribe to some of these events:

@Component
@RepositoryEventHandler(Employee.class)
public class EventHandler {
private final SimpMessagingTemplate websocket;

private final EntityLinks entityLinks;

@Autowired
public EventHandler(SimpMessagingTemplate websocket, 
			EntityLinks entityLinks) {
	this.websocket = websocket;
	this…

Spring XD 1.3 M1 released

Releases | Mark Pollack | October 08, 2015 | ...

On behalf of the Spring XD team, I am very pleased to announce the first milestone release of Spring XD 1.3

This release includes bug fixes and some enhancements:

  • Hadoop distribution version updates to Apache Hadoop 2.7.1 and Hortonworks Data Platform 2.3. Pivotal Hadoop 2.1, 3.0 and Cloudera Hadoop 5.4
  • Spark 1.3.1 Support
  • Cassandra Sink
  • Header Enricher Processor
  • Bug fixes to the Flo Designer UI and Admin UI
  • Gpfdist sink now supports update operations and full range of control file options
  • Update to Spring Integration 4.2 which provides performance improvements when monitoring is enabled.
  • Upgrade to Spring Data Gosling Release train

The Spring Boot Dashboard in STS - Part 1: Local Boot Apps

Engineering | Martin Lippert | October 08, 2015 | ...

Welcome Spring community,

This is the first of three blog entries introducing you to the new Spring Boot Dashboard in STS. You will see how to use the Spring Boot Dashboard in the IDE, learn about the various features it provides, and how it helps you while developing applications based on Spring Boot. Since the Spring Boot Dashboard was introduced in the recently released STS 3.7.1, you will need that version to follow this blog series. If you don't have that installed yet, please go to http://spring.io/tools/ and grab your copy of it.

Introduction

Spring Boot is now a widely adopted technology to simplify your life when implementing Spring applications for the enterprise. Especially suitable for creating microservice-based applications, it has changed the way we think about small and easy to configure Spring applications dramatically. Together with Spring Cloud, it opens the door to truly cloud-native applications, composed out of probably many microservices.

This dramatic shift in our architectural thinking needs to be reflected in our IDEs as well. Most of our traditional Java IDEs out there were invented not only in the pre-cloud-native era, but in the pre-cloud and to a certain degree in the pre-distributed era of programming. The same is true for the Spring Tool Suite and its base, the Eclipse IDE. It is time to push those IDEs into the cloud-native era. This was the starting point for the Spring Boot Dashboard. Its focus is to help you deal with a potentially larger number of Spring-Boot-based microservice applications and make your life as a developer a lot easier when working on those projects in your IDE.

The Spring Boot Dashboard

Starting small and incrementally, the Spring Boot Dashboard comes as an additional view in STS/Eclipse. You can open it by pressing the Spring Boot button in your main toolbar. It opens up a simple view that is in sync with your workspace projects, showing those projects of your workspace that are Spring Boot projects.

The main purpose of the Boot Dashboard is to give you quick access to the things you do every day, every hour, or even more frequently. You can quickly start your boot apps (in run or debug mode) by selecting them in the boot dashboard and pressing the "run" or "debug" action in the toolbar. There is no faster way to launch your boot app than this. And since you probably are going to change code and want to restart your app, the action lets you restart your boot app, if it is already running. Change your code, press the "run" button in the boot dashboard, and your boot app gets stopped and restarted for you. Again, a simple one-click action.

The great thing about these actions (and many more) in the boot dashboard is that they operate on single or multiple projects at the same time. If you want to start or stop a bunch of boot apps at the same time, for example to startup a set of collaborating services, just select them all in the dashboard and press "run". That's it.

As soon as you adopt Spring Boot 1.3 in your projects, you will notice additional goodies showing up in the Boot Dashboard. As soon as your boot app is being started, the boot dashboard visualizes that the app is starting - and it distinguishes between its startup phase (the VM is running, but the app is still initializing) and it is truly running and ready to use. The progress icon indicates the app is still starting up, the green "up" icon shows up as soon as the app is fully initialized and running. You don't need to observe the log output until some "server started" message shows up or something like that. The boot dashboards icons will let you know.

Once the app is running, the port that it listens on will show up in the boot dashboard - for your convenience. You don't have to scan the log output anymore to find out what port is being used by the app. The dashboard displays that information automatically. And in case you would like to jump to the console output of a running boot app, there is a quick action for that as well.

Often there is no need anymore to know about the port of a running app - since you don't have to open a browser tab for the app yourself. Double-click on the project in the boot dashboard and it will open a new browser tab for you - directly navigating to the apps default URL.

By default, this opens an Eclipse/STS internal browser view. If you prefer to use an external browser, you can set this in the preferences.

In case this default URL is not the one you would like to visit by default, you can customize that. Open the properties view, select the project in the boot dashboard and enter the default URL extension that you prefer. The double-click will open the default URL of the app + your customized extension to it.

In case you are not sure what URL extensions your application defines, you can select the “Request Mappings” tab in the properties view. All the request mappings of the running app are listed - your self-defined ones at the top, the ones coming from libraries at the bottom of that list. Double-clicking on the URL extension opens a browser for that extension, double-clicking on the code pointer opens the corresponding file of your project in an editor and jumps to the line that defines the request mapping.

The more microservice projects you have in your workspace, the more likely it is that you don’t work on all of them at the same time. You would like to focus on a subset. In Eclipse/STS, you might have created a working set, for example. The boot dashboard allows you to tag projects with an arbitrary number of tags (again, in the properties view). Those tags can then be used in the filter box (at the top of the boot dashboard) to reduce the number of projects that show up in the boot dashboard.

Outlook

The second part of this series will introduce you to the Cloud Foundry integration of the Boot dashboard, how to deploy microservices to CF from within the boot dashboard, and how to use local boot apps in combination with those deployed on CF.

Spring REST Docs 1.0.0.RELEASE

Releases | Andy Wilkinson | October 07, 2015 | ...

I'm delighted to announce that Spring REST Docs 1.0.0.RELEASE has been released. It's available from Maven Central and our release repository.

What is Spring REST Docs?

Spring REST Docs helps you to document RESTful services. It combines hand-written documentation written with Asciidoctor and auto-generated snippets produced with Spring MVC Test. This approach frees you from the limitations imposed by tools like Swagger. It helps you to produce documentation that is accurate, concise, and well-structured. This documentation then allows your users to get the information they need with a minimum…

This Week in Spring - October 6th, 2015

Engineering | Josh Long | October 07, 2015 | ...

Welcome to another installation of This Week in Spring! As usual we've got a lot to cover this week so let's get to it!

A brief update on Java EE 7 adoption

News | Juergen Hoeller | October 06, 2015 | ...

A reminder: Every time somebody shows you a survey result with a Java EE 7 usage column, in particular when talking about production usage, double-check what they actually asked for. Does Hibernate 4.3 usage count as Java EE 7, just because it's JPA 2.1 (EE 7 level but run standalone)? Does Tomcat 8 usage count as Java EE 7, just because it's Servlet 3.1? And of course, does running a Spring application with any such individual providers count as EE 7?

Take such statistics with a big grain of salt: They typically do not ask for "native Java EE 7 platform usage" but are being presented that way eventually. Why is it a safe assumption that they did not ask for full Java EE 7 platform usage in production? Well, remember my blog post from back in June, which is still as valid in late 2015. In the meantime, the only real news is that there is no news since IBM released their EE 7 support in WebSphere's Liberty Profile. All in all, responders to such survey…

Evolving Spring Initializr

Engineering | Brian Clozel | October 06, 2015 | ...

We're happy to release today the new version of Spring Initializr at https://start.spring.io !

What started out as a small, in-house web application that generates Spring Boot projects, grew into something bigger than we expected. You can now use Spring Initializr on the web, in your favorite IDE (Eclipse STS and IntelliJ IDEA) and even with your command-line tools (try curl https://start.spring.io).

In the meantime, the Spring portfolio is growing and we received a lot of useful feedback from the Spring community. Because nothing beats actual data, we've improved the service to export its metrics to a centralized redis instance, before the summer. This allows us to keep a reliable set of statistics for a long period of activity (and regardless of the number of instances we deploy on Pivotal Web Services

Spring Tool Suite 3.7.1 released

Releases | Martin Lippert | October 06, 2015 | ...

Dear Spring Community,

I am happy to announce the 3.7.1 release of the Spring Tool Suite, our Eclipse-based tooling.

Highlights from this release include:

  • updated to Eclipse Mars.1 (4.5.1), including a number of fixes for JDT and m2e
  • updated to Pivotal tc Server 3.1.2
  • various improvements to the Spring Boot YML properties editor
  • improvements to the Spring Boot Starter wizard
  • new support for Spring Boot Devtools, including ability to attach Java debugger to CF deployed apps.
  • the new spring boot dashboard, currently in beta, but definitely the highlight of this release

To download the distributions, please go visit:

Detailed new and noteworthy notes can be found here: STS 3.7.1 New & Noteworthy.

STS 3.7.2 is scheduled to ship in December 2015.

Enjoy!

This Week in Spring - September 29, 2015

Engineering | Josh Long | September 30, 2015 | ...

Welcome to another installation of This Week in Spring! To those of you reading from the US, let me be the first to wish you a very happy national coffee day! As usual, we've got a lot to cover so let's get to it!

React.js and Spring Data REST: Part 3 - Conditional Operations

Engineering | Greg L. Turnquist | September 29, 2015 | ...
To see updates to this code, visit our React.js and Spring Data REST tutorial.

In the previous session, you found out how to turn on Spring Data REST’s hypermedia controls, have the UI navigate by paging, and dynamically resize based on changing the page size. You added the ability to create and delete employees and have the pages adjust. But no solution is complete with taking into consideration updates made by other users on the same bit of data you are currently editing.

Feel free to grab the code from this repository and follow along. This session is based on the previous session’s app with extra things added.

To PUT or not to PUT, that is the question

When you fetch a resource, there is risk is that it might go stale if someone else updates it. To deal with this, Spring Data REST integrates two technologies: versioning of resources and ETags.

By versioning resources on the backend and using ETags in the frontend, it is possible to conditially PUT a change. In other words, you can detect if a resource has changed and prevent a PUT (or a PATCH) from stomping on someone else’s update. Let’s check it out.

Versioning REST resources

To support versioning of resources, define a version attribute for your domain objects that need this type of protection.

src/main/java/com/greglturnquist/payroll/Employee.java
@Data
@Entity
public class Employee {
private @Id @GeneratedValue Long id;
private String firstName;
private String lastName;
private String description;

private @Version @JsonIgnore Long version;

private Employee() {}

public Employee(String firstName, String lastName, String description) {
	this.firstName = firstName;
	this.lastName = lastName;
	this.description = description;
}

}

  • The version field is annoated with javax.persistence.Version. It causes a value to be automatically stored and updated everytime a row is inserted and updated.

When fetching an individual resource (not a collection resource), Spring Data REST will automatically add an ETag response header with the value of this field.

Fetching individual resources and their headers

In the previous session you used the collection resource to gather data and populate the UI’s HTML table. With Spring Data REST, the _embedded data set is considered a preview of data. While useful for glancing at data, to get headers like ETags, you need to fetch each resource individually.

In this version, loadFromServer is updated to fetch the collection and then use the URIs to retrieve each individual resource.

src/main/resources/static/app.jsx - Fetching each resource
loadFromServer: function (pageSize) {
    follow(client, root, [
        {rel: 'employees', params: {size: pageSize}}]
    ).then(employeeCollection => {
        return client({
            method: 'GET',
            path: employeeCollection.entity._links.profile.href,
            headers: {'Accept': 'application/schema+json'}
        }).then(schema => {
            this.schema = schema.entity;
            this.links = employeeCollection.entity._links;
            return employeeCollection;
        });
    }).then(employeeCollection => {
        return employeeCollection.entity._embedded.employees.map(employee =>
                client({
                    method: 'GET',
                    path: employee._links.self.href
                })
        );
    }).then(employeePromises => {
        return when.all(employeePromises);
    }).done(employees => {
        this.setState({
            employees: employees,
            attributes: Object.keys(this.schema.properties),
            pageSize: pageSize,
            links: this.links
        });
    });
},
  1. The follow() function goes to the employees collection resource.
  2. The then(employeeCollection ⇒ …​) clause creates a call to fetch JSON Schema data. This has a sub-then clause to store the metadata and navigational links in the <App/> component.
    • Notice that this embedded promise returns the employeeCollection. That way, the collection can be passed onto the next call while letting you grab the metadata along the way.
  3. The second then(employeeCollection ⇒ …​) clause converts the collection of employees into an array of GET promises to fetch each individual resource. This is what you need to fetch an ETag header for each employee.
  4. The then(employeePromises ⇒ …​) clause takes the array of GET promises and merges them into a single promise with when.all(), resolved when all the GET promises are resolved.
  5. loadFromServer wraps up with done(employees ⇒ …​) where the UI state is updated using this amalgamation of data.

This chain is implemented in other places as well. For example, onNavigate(), which is used to jump to different pages, has been updated to fetch individual resources. Since it’s mostly the same as what’s shown above, it’s been left out of this session.

Updating existing resources

In this session, you are adding an UpdateDialog React component to edit existing employee records.

src/main/resources/static/app.jsx - UpdateDialog component
var UpdateDialog = React.createClass({
handleSubmit: function (e) {
    e.preventDefault();
    var updatedEmployee = {};
    this.props.attributes.forEach(attribute =&gt; {
        updatedEmployee[attribute] = React.findDOMNode(this.refs[attribute]).value.trim…

Get the Spring newsletter

Thank you!

Get ahead

VMware offers training and certification to turbo-charge your progress.

Learn more

Get support

Spring Runtime offers support and binaries for OpenJDK™, Spring, and Apache Tomcat® in one simple subscription.

Learn more

Upcoming events

Check out all the upcoming events in the Spring community.

View all