Spring Cloud Data Flow: Native Cloud Orchestration Services For Microservice Applications On Modern Runtimes 1st Edition Felipe Gutierrez
Spring Cloud Data Flow: Native Cloud Orchestration Services For Microservice Applications On Modern Runtimes 1st Edition Felipe Gutierrez
com
https://textbookfull.com/product/spring-cloud-data-flow-
native-cloud-orchestration-services-for-microservice-
applications-on-modern-runtimes-1st-edition-felipe-
gutierrez/
OR CLICK BUTTON
DOWNLOAD NOW
https://textbookfull.com/product/cloud-native-java-designing-
resilient-systems-with-spring-boot-spring-cloud-and-cloud-foundry-1st-
edition-long/
textboxfull.com
https://textbookfull.com/product/spring-boot-up-and-running-building-
cloud-native-java-and-kotlin-applications-mark-heckler/
textboxfull.com
https://textbookfull.com/product/spring-boot-messaging-messaging-apis-
for-enterprise-and-integration-solutions-felipe-gutierrez/
textboxfull.com
https://textbookfull.com/product/cloud-native-data-center-
networking-1st-edition-dinesh-g-dutt/
textboxfull.com
https://textbookfull.com/product/programming-kubernetes-developing-
cloud-native-applications-1st-edition-michael-hausenblas/
textboxfull.com
https://textbookfull.com/product/kubernetes-patterns-reusable-
elements-for-designing-cloud-native-applications-1st-edition-bilgin-
ibryam/
textboxfull.com
https://textbookfull.com/product/cloud-native-go-building-reliable-
services-in-unreliable-environments-1st-edition-matthew-a-titmus/
textboxfull.com
https://textbookfull.com/product/cloud-native-go-building-reliable-
services-in-unreliable-environments-1st-edition-titmus-matthew-a/
textboxfull.com
Spring Cloud
Data Flow
Native Cloud Orchestration Services
for Microservice Applications on
Modern Runtimes
—
Felipe Gutierrez
Spring Cloud Data Flow
Native Cloud Orchestration Services
for Microservice Applications on Modern
Runtimes
Felipe Gutierrez
Spring Cloud Data Flow: Native Cloud Orchestration Services for Microservice
Applications on Modern Runtimes
Felipe Gutierrez
Albuquerque, NM, USA
■
■Part I: Introductions��������������������������������������������������������������������������� 1
■
■Chapter 1: Cloud and Big Data������������������������������������������������������������������������������� 3
A Little Data Science�������������������������������������������������������������������������������������������������������� 3
The Cloud������������������������������������������������������������������������������������������������������������������������� 4
Cloud Technology and Infrastructure������������������������������������������������������������������������������������������������������ 5
■
■Chapter 3: Spring Integration������������������������������������������������������������������������������ 33
Integration Patterns�������������������������������������������������������������������������������������������������������� 33
Messaging���������������������������������������������������������������������������������������������������������������������� 34
Spring Integration����������������������������������������������������������������������������������������������������������� 35
Movie App Specification Requirements������������������������������������������������������������������������������������������������ 35
Creating the Movie App: Part I�������������������������������������������������������������������������������������������������������������� 36
Creating a Movie App: Part II (External)������������������������������������������������������������������������������������������������ 52
Summary������������������������������������������������������������������������������������������������������������������������ 69
■
■Chapter 4: Spring Batch�������������������������������������������������������������������������������������� 71
Spring Batch������������������������������������������������������������������������������������������������������������������� 71
Programming Model����������������������������������������������������������������������������������������������������������������������������� 71
Spring Batch Features�������������������������������������������������������������������������������������������������������������������������� 72
Movie Batch App Using Declarative XML���������������������������������������������������������������������������������������������� 72
Movie Batch App Using JavaConfig������������������������������������������������������������������������������������������������������ 80
Summary������������������������������������������������������������������������������������������������������������������������ 87
■
■Chapter 5: Spring Cloud�������������������������������������������������������������������������������������� 89
Microservices����������������������������������������������������������������������������������������������������������������� 89
The Twelve-Factor App��������������������������������������������������������������������������������������������������� 90
Spring Cloud������������������������������������������������������������������������������������������������������������������� 92
Spring Cloud Config������������������������������������������������������������������������������������������������������������������������������ 92
vi
■ Table of Contents
Summary���������������������������������������������������������������������������������������������������������������������� 207
■
■Chapter 8: Spring Cloud Data Flow: Introduction and Installation�������������������� 209
Spring Cloud Data Flow������������������������������������������������������������������������������������������������ 209
Features���������������������������������������������������������������������������������������������������������������������������������������������� 210
vii
■ Table of Contents
Summary���������������������������������������������������������������������������������������������������������������������� 262
■
■Part II: Spring Cloud Data Flow: Internals�������������������������������������� 263
■
■Chapter 9: Spring Cloud Data Flow Internals���������������������������������������������������� 265
Spring Cloud Data Flow Architecture��������������������������������������������������������������������������� 265
Client Tools: cURL Command, Data Flow Shell, Java Client, Dashboard����������������������� 268
Using cURL, Httpie, and jq������������������������������������������������������������������������������������������������������������������ 271
Using Spring Cloud Data Flow Shell��������������������������������������������������������������������������������������������������� 279
Using the Dashboard�������������������������������������������������������������������������������������������������������������������������� 285
Creating the Stream Programmatically���������������������������������������������������������������������������������������������� 299
Summary���������������������������������������������������������������������������������������������������������������������� 310
■
■Chapter 10: Custom Stream Apps with Spring Cloud Data Flow����������������������� 311
Custom Stream Apps: A Quick Review������������������������������������������������������������������������� 311
Custom Stream Apps in Spring Cloud Data Flow��������������������������������������������������������� 312
Movie Web App: movie-source����������������������������������������������������������������������������������������������������������� 312
Movie IMDB App: movie-processor����������������������������������������������������������������������������������������������������� 319
Movie Log App: movie-sink����������������������������������������������������������������������������������������������������������������� 326
Packaging and Deploy Stream Apps��������������������������������������������������������������������������������������������������� 328
Registering Stream Apps�������������������������������������������������������������������������������������������������������������������� 331
Create and Deploy Custom Streams��������������������������������������������������������������������������������������������������� 335
Summary���������������������������������������������������������������������������������������������������������������������� 339
viii
■ Table of Contents
■
■Chapter 11: Task and Batch Apps with Spring Cloud Data Flow����������������������� 341
Spring Cloud Task Primer��������������������������������������������������������������������������������������������� 341
Simple Task Demo������������������������������������������������������������������������������������������������������������������������������ 342
Summary���������������������������������������������������������������������������������������������������������������������� 381
■
■Chapter 12: Monitoring������������������������������������������������������������������������������������� 383
Micrometer������������������������������������������������������������������������������������������������������������������� 383
Health Checks and Monitoring Stream Apps���������������������������������������������������������������� 385
Monitoring Task Apps��������������������������������������������������������������������������������������������������� 387
Movie Stream Pipeline DSL: Putting It All Together������������������������������������������������������ 388
Stream Pipeline DSL��������������������������������������������������������������������������������������������������������������������������� 391
Task Creating�������������������������������������������������������������������������������������������������������������������������������������� 393
Stream Deployment���������������������������������������������������������������������������������������������������������������������������� 393
Summary���������������������������������������������������������������������������������������������������������������������� 397
■
■Index������������������������������������������������������������������������������������������������������������������ 399
ix
About the Author
Felipe Gutierrez is a cloud solutions software architect, with a bachelor’s degree and a master’s degree in
computer science from Instituto Tecnólogico y de Estudios Superiores de Monterrey, Ciudad de Mexico.
With more than 25 years of IT experience, he has developed programs for companies in multiple vertical
industries, including government, retail, health care, education, and banking. Currently, he works as a senior
cloud application architect for IBM, specializing in Red Hat OpenShift, IBM Cloud, app modernization,
Cloud Foundry, Spring Framework, Spring Cloud Native applications, Groovy, and RabbitMQ, among other
technologies. He has worked as a solutions architect for companies like VMware, Nokia, Apple, Redbox, and
Qualcomm. Felipe is the author of Introducing Spring Framework (Apress, 2014), Pro Spring Boot (Apress,
2016), and Spring Boot Messaging (Apress, 2017).
About the Technical Reviewer
I would like to express all my gratitude to the Apress team: Steve Anglin for accepting my proposal, Mark
Powers for keeping me on track and for his patience, and the rest of the Apress team involved in this project.
Thanks to everybody for making this possible.
Thanks to my technical reviewer, Manuel Jordan, for all the details and effort in his reviews, and the
entire Spring team for creating this amazing technology.
I want to dedicate this book to my grandparents: Juan Gutierrez and Baciliza Rivero on my dad’s side,
and Simon Cruz and Elvira Galindo on my mom’s side. Thanks for being part of my life. I miss you so much.
—Felipe Gutierrez
PART I
Introductions
CHAPTER 1
The digital universe consists of an estimated 44 zettabytes of data. A zettabyte is 1 million petabytes, or
1 billion terabytes, or 1 trillion gigabytes. In 2019, Google processed approximately 3.7 million queries,
YouTube recorded 4.5 million viewed videos, and Facebook registered 1 million logins every 60 seconds.
Imagine the computer power to process all these requests, data ingestion, and data manipulation. Common
sense tells us that the big IT companies use a lot of hardware to preserve data. A lot of storage needs to be
incorporated to prevent limits of capacity.
How does an IT company deal with challenges like data overload, rising costs, or skill gaps? In recent
years, big IT companies have heavily invested in developing strategies that use enterprise data warehouses
(EDW) to serve as central data systems that report, extract, transform, and load (ETL) processes from
different sources. Today, both users and devices (thermostats, light bulbs, security cameras, coffee
machines, doorbells, seat sensors, etc.) ingest data.
Companies such as Dell, Intel, and Cloudera—to name a few—work together to create hardware and
storage solutions that help other companies grow and become faster and more scalable.
We need to have the right tools, platform, infrastructure, and software engineering knowledge to
innovate and create. Machine learning should rely on a programming language that feels comfortable
and easy to learn (like Python). The platform should have the right engines for processing the data. The
infrastructure should be reliable, secure, and redundant. The development techniques should create
awesome enterprise solutions that benefit not only the company but all its users around the world.
The Cloud
Over the past decade, many companies have gone into the so-called cloud, or they are cloud native, or they
are in the cloud computing era; but what does that even mean? Several companies have said that they were
always in the cloud because all their services live outside the company, managed by a third party, and they
have faster responses if there is an outage. But is that accurate? Or does cloud mean architectural computing
in which servers, networks, storage, development tools, and applications are enabled through the Internet?
In my opinion, we have Internet access through a public cloud environment, where users can “plug
into” data and applications at any given time and place through an Internet connection. I see the cloud as
a new measure service with a pay-as-you-go model, where you only pay for what you are using, from any
server, network, storage, bandwidth, application, or more—very similar to an electric or water company that
charges based on consumption.
4
Chapter 1 ■ Cloud and Big Data
I also see the cloud as an on-demand self-service. You can request any of those services, and they are
provisioned very quickly with a few clicks.
I can see the cloud as a multitenancy model where a single instance of an application, network, or
server is shared across multiple users. This is referred to as shared resource pooling. Once you finish using it,
it returns to the pool to wait for another user to request it.
I can see the cloud as an elastic platform where the resources quickly scale up or down as needed (see
Figure 1-2).
5
Chapter 1 ■ Cloud and Big Data
Storage, servers, or VMs are needed to implement cloud infrastructure. Managed services, hybrid
operations, and data security and management are also required. Services that allow the companies to use
their data against all these new machine learning tools and apply new artificial intelligence algorithms for
system analytics to help with fraud detection help with decision making, to name a few growing features of
data processing (see Figure 1-3).
6
Chapter 1 ■ Cloud and Big Data
Technologies like Apache Hadoop distribute large data sets across clusters. Apache Flume is a simple
and flexible architecture for streaming dataflows and a service for collecting, aggregating, and moving large
amounts of log data. Apache Sqoop is a batch tool for transferring bulk data between Apache Hadoop and
structured datastores (such as relational databases); it solves some of the data wrangling that you need to do.
A new wave of programming languages can process a large amount of data. These include languages
like R, Python, and Scala, and a set of libraries and frameworks, like MadLib, for machine learning and
expert systems (see Figures 1-5 and 1-6).
New protocols for messaging brokers emerge every day. Should we learn all these new technologies?
Or should we hire people with all these skill sets? I think we should at least have a technology that takes care
of communication. Well, we do: Spring Cloud Stream and the orchestrator, Spring Cloud Data Flow (see
Figure 1-7).
7
Chapter 1 ■ Cloud and Big Data
I’ll discuss these two technologies. If you are a Spring developer, you don’t need to learn any new APIs
for messaging; you can work with what you already know—Java and Spring. If you are new to Spring, in the
next two chapters, I give a quick tour of Spring Boot, Spring Integration, and Spring Batch and show you how
to use them. These three technologies are the core of Spring Cloud Stream and Spring Cloud Data Streams
(see Figure 1-7).
Next, you create your first Stream applications, which can connect regardless of the messaging broker.
That’s right; it doesn’t matter which broker you set up between multiple Streams apps. Spring Cloud Stream
has that capability. You will develop custom streams and create a custom binder that allows you to hide any
API from a messaging broker.
Finally, I talk about Spring Cloud Data Flow and its components and how to create apps, streams, and
tasks and monitor them (see Figure 1-7).
S
ummary
In this chapter, I talked about big data and new ways to improve services using cloud infrastructures that
offer out-of-the-box solutions. Every company needs to have visibility, speed, the ability to enter the market
quickly, and time to react.
In this short chapter, I wanted to set the context for this book. In the next chapters, I talk about
technologies that help you use big data to create enterprise-ready solutions.
8
CHAPTER 2
Spring Boot
One way to build cloud-native applications is to follow the Twelve-Factor App guidelines
(https://12factor.net) that facilitate running applications in any cloud environment. Some of these
principles, like dependencies declaration (factor II), configuration (factor III), and port binding (factor VII),
among others, are supported by Spring Boot! Spring Boot is a microservice and cloud-ready framework.
Why Spring Boot and not just Spring? Or maybe another technology, like NodeJS or the Go language?
Spring Boot is a technology that has no comparison because is backed by the most-used framework in the
Java community and lets you create an enterprise-ready application with ease. Other languages require
you to do a lot of manual setup and coding. Spring Boot provides it for you. Even though technologies like
NodeJS have hundreds of libraries, it is no match at the enterprise level like Spring, in my opinion. Don’t get
me wrong. I’m not saying that other technologies are bad or not useful, but if you want to build a fast, fine-
grained, enterprise application, only Spring Boot offers minimal configuration and code. Let’s look at why
Spring Boot is important and how it helps you create cloud-native applications.
Spring Framework
Let’s back up a little bit and talk about the Spring Framework. With the Spring Framework, you can
create fine-grained enterprise apps, but you need to know how it works, and most importantly, how
to configure it. Configuration is one of the key elements of the Spring Framework. You can decouple
custom implementations, DB connections, and calls to external services, making Spring Framework more
extensible, easy to maintain, and run. At some point, you need to know all the best practices to apply to a
Spring app. Let’s start with a simple Spring app that demonstrates how the Spring Framework works.
A
Directory Application
Let’s suppose that you need to create a Spring application that saves people’s contact information, such as
names, emails, and phone numbers. It is a basic directory app that exposes a REST API with persistence in
any DB engine, and it can be deployed in any compliant J2EE server. The following are the steps to create
such an application.
1. Install a building tool like Maven or Gradle to compile and build the source
code’s directory structure. If you come from a Java background, you know that
you need a WEB-INF directory structure for this app.
2. Create web.xml and application-context.xml files. The web.xml file has the
org.springframework.web.servlet.DispatcherServlet class, which acts as a
front controller for Spring-based web applications.
3. Add a listener class that points to the application-context.xml file, where you
declare all the Spring beans or any other configuration needed for your app. If
you omit the listener section, you need to name your Spring beans declaration
file the same as the DispatcherServlet.
4. In the application-context.xml file, add several Spring beans sections to
cover every detail. If you are using JDBC, you need to add a datasource, init SQL
scripts, and a transaction manager. If you are using JPA, you need to add a JPA
declaration (a persistence.xml file where you configure your classes and your
primary unit) and an entity manager to handle sessions and communicate with
the transaction manager.
5. Because this is a web app, it is necessary to add some Spring beans sections
in the application-context.xml file about HTTP converters that expose
JSON views and MVC-driven annotations to use the @RestController and
@RequestMapping (or @GetMapping, @PostMapping, @DeleteMapping, etc.)
among other Spring MVC annotations.
6. If you are using JPA (the easiest way to do persistence with minimal effort),
specify the repositories and the classes’ location with the
@EnableJpaRepositories annotation.
7. To run the app, package your application in a WAR format. You need to install an
application server that is compliant with J2EE standards and then test it.
If you are an experienced Spring developer, you know what I’m talking about. If you are a newbie, then
you need to learn all the syntax. It’s not too difficult, but you need to spend some time on it. Or perhaps there is
another way. Of course, there is. You can use annotation-based configuration or a JavaConfig class to set up the
Spring beans, or you can use a mix of both. In the end, you need to learn some of the Spring annotations that
help you configure this app. You can review the source code (ch02/directory-jpa) on this book’s web site.
Let’s review some of this application’s code. Remember, you need to create a Java web structure (see
Figure 2-1).
Figure 2-1 shows a Java web-based directory structure. You can delete the index.jsp file, open the web.
xml file, and replace it all with the content shown in Listing 2-1.
<web-app>
<display-name>Archetype Created Web Application</display-name>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/application-context.xml</param-value>
</context-param>
<servlet>
<servlet-name>app</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value></param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>app</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
Listing 2-1 shows you how to add a Spring servlet (DispatcherServlet, a front controller pattern) that is
the main servlet to attend any request from the user.
Next, let’s create the application-context.xml file by adding the content in Listing 2-2.
11
Chapter 2 ■ Spring Boot
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xsi:schemaLocation="
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/
spring-mvc.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/
spring-tx.xsd
http://www.springframework.org/schema/jdbc https://www.springframework.org/schema/
jdbc/spring-jdbc.xsd
http://www.springframework.org/schema/data/jpa https://www.springframework.org/
schema/data/jpa/spring-jpa.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/
schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.
org/schema/context/spring-context.xsd">
<mvc:annotation-driven />
<tx:annotation-driven />
<jpa:repositories base-package="com.apress.spring.directory.repository" entity-manager-
factory-ref="localContainerEntityManagerFactoryBean" />
<context:component-scan base-package="com.apress.spring.directory" />
<mvc:annotation-driven content-negotiation-manager="contentNegotiationManager">
<mvc:message-converters>
<bean class="org.springframework.http.converter.json.
MappingJackson2HttpMessageConverter">
<property name="objectMapper" ref="objectMapper"/>
</bean>
<bean class="org.springframework.http.converter.xml.
MappingJackson2XmlHttpMessageConverter">
<property name="objectMapper" ref="xmlMapper"/>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
12
Chapter 2 ■ Spring Boot
</value>
</property>
</bean>
<bean id="localContainerEntityManagerFactoryBean"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">create-drop</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.H2Dialect</prop>
</props>
</property>
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.h2.Driver" />
<property name="url" value="jdbc:h2:mem:testdb" />
<property name="username" value="sa" />
<property name="password" value="" />
</bean>
Listing 2-2 shows the application-context.xml file, in which you add all the necessary configuration
for the Spring container, which is where all your classes are initialized and wired up.
Before reviewing each tag and the way it is declared, see if you can guess what each does and why it is
configured the way it is. Look at the naming and references between declarations.
If you are new to Spring, I recommend you look at the Pro Spring series published by Apress. These
books explain every aspect of this declarative form of configuring Spring.
Next, add the following classes: Person, PersonRepository, and PersonController, respectively (see
Listings 2-3, 2-4, and 2-5).
13
Chapter 2 ■ Spring Boot
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class Person {
@Id
private String email;
private String name;
private String phone;
public Person() {
}
Listing 2-3 shows the Person class that uses all the JPA (Java Persistence API) annotations, so it’s easy to
use, and no more direct JDBC.
14
Chapter 2 ■ Spring Boot
import com.apress.spring.directory.domain.Person;
import org.springframework.data.repository.CrudRepository;
Listing 2-4 shows the PersonRepository interface that extends from another CrudRepository interface.
Here it uses all the power of Spring Data and Spring Data JPA to create a repository pattern based on the
entity class and its primary key (in this case, a String type). In other words, there is no need to create any
CRUD implementations—let Spring Data and Spring Data JPA take care of that.
import com.apress.spring.directory.domain.Person;
import com.apress.spring.directory.repository.PersonRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.UriComponents;
import org.springframework.web.util.UriComponentsBuilder;
@Controller
public class PersonController {
@RequestMapping(value = "/people",
method = RequestMethod.GET,
produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE})
@ResponseBody
public Iterable<Person> getPeople() {
log.info("Accessing all Directory people...");
return personRepository.findAll();
}
15
Chapter 2 ■ Spring Boot
@RequestMapping(value = "/people",
method = RequestMethod.POST,
consumes = MediaType.APPLICATION_JSON_VALUE,
produces = {MediaType.APPLICATION_JSON_VALUE})
@ResponseBody
public ResponseEntity<?> create(UriComponentsBuilder uriComponentsBuilder,
@RequestBody Person person) {
personRepository.save(person);
UriComponents uriComponents =
uriComponentsBuilder.path("/people/{id}").buildAndExpand(person.getEmail());
return ResponseEntity.created(uriComponents.toUri()).build();
}
@RequestMapping(value = "/people/search",
method = RequestMethod.GET,
consumes = MediaType.APPLICATION_JSON_VALUE,
produces = {MediaType.APPLICATION_JSON_VALUE})
@ResponseBody
public ResponseEntity<?> findByEmail(@RequestParam String email) {
log.info("Looking for {}", email);
return ResponseEntity.ok(personRepository.findById(email).orElse(null));
}
@RequestMapping(value = "/people/{email:.+}",
method = RequestMethod.DELETE)
@ResponseBody
public ResponseEntity<?> deleteByEmail(@PathVariable String email) {
log.info("About to delete {}", email);
personRepository.deleteById(email);
return ResponseEntity.accepted().build();
}
}
Listing 2-5 shows the implementation of the PersonController class for any user request/response.
There are many ways to implement a web controller in Spring, such as using @RestController. Avoid writing
@ResponseBody in each method, or use dedicated annotations like @GetMapping, @PostMapping, and
@DeleteMapping instead of @RequestMapping.
Next, create the SQL files that initialize the database (see Listings 2-6 and 2-7).
16
Chapter 2 ■ Spring Boot
Listing 2-7 shows a few records to insert when the app starts up. Next, because this app is using JPA,
it is necessary to provide a persistence.xml file. There is another option—you can add a bean declaration to
application-context.xml and declare the persistence unit required for the JPA engine to work (see Listing 2-8).
Listing 2-8 shows the required JPA file to declare the persistence unit. You can declare this as a property
in the localContainerEntityManagerFactoryBean bean declaration (persistenceUnitName property).
Next is one of the most important files. This app was created using Maven as a building tool. Let’s create
a pom.xml file at the root of the project (see Listing 2-9).
<properties>
<java.version>1.8</java.version>
<servlet.version>3.1.0</servlet.version>
<spring-framework.version>5.2.2.RELEASE</spring-framework.version>
<spring-data.jpa>2.2.3.RELEASE</spring-data.jpa>
<slf4j.version>1.7.25</slf4j.version>
<logback.version>1.2.3</logback.version>
<h2>1.4.199</h2>
<jackson>2.10.1</jackson>
</properties>
<dependencies>
17
Chapter 2 ■ Spring Boot
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>${spring-data.jpa}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
</dependency>
18
Random documents with unrelated
content Scribd suggests to you:
comuni in tutte le isole della Malesia e che le eleganti malesi
racchiudono in bolle di vetro, puntandosele fra i capelli con dei
bellissimi spilloni d’argento.
Era già trascorsa un’ora senza che fosse accaduto alcunchè di
straordinario, quando Cornelio credette di vedere una massa oscura
attraversare rapidamente il fiume, descrivendo una parabola assai
allungata. Si era staccata da un grande albero situato sulla sponda
destra ed era scomparsa sotto i boschi della sponda opposta.
— Wan-Horn, hai veduto? chiese, raccogliendo precipitosamente il
fucile.
— Non ho veduto nulla, nè udito nulla, signor Cornelio, rispose il
marinaio.
— M’è passata dinanzi agli occhi una cosa nera, che non ho potuto
ben distinguere.
— Sarà stato un uccello.
— No, Wan-Horn, era grosso assai e non aveva le forme d’un
volatile.
— Cosa volete che sia?
— Non lo so, ma se fosse qualche proiettile inviatoci dai papuasi?
— Non fanno uso che di freccie e di lancie, signor Cornelio...
— Lo so, ma... guarda!
Una massa nera, un’altra senza dubbio, si era staccata da un albero
della sponda destra, aveva attraversato il fiume con uno strano
dondolìo, producendo una lieve corrente d’aria ed era scomparsa fra
le piante dell’opposta riva.
— L’hai veduta, Horn? chiese Cornelio.
— Sì, e so cos’era.
— Un proiettile?
— No, signor Cornelio, era uno di quei volatili che i malesi chiamano
kubung, noi gatti o volpi volanti e gli scienziati galeopithecus, se non
erro.
— Che animali sono?
— Sembrano scimmie, più che volpi; sono alte mezzo metro, con
una testa piuttosto piccola che rassomiglia un po’ a quella degli
scoiattoli, col pelo rosso-oscuro, e spiccano delle vere volate di
sessanta metri. Ve ne sono pure delle altre che hanno una coda
lunga un buon piede, ma spiccano dei voli meno lunghi.
— Ma come fanno a volare?
— Colle ali.
— Delle scimmie colle ali? Ma tu sogni, Horn.
— No, signor Cornelio, ma non vi dico che le loro ali siano uguali a
quelle degli uccelli, tutt’altro. Hanno una specie di membrana che
parte dalle zampe anteriori, si unisce a quelle posteriori e si prolunga
fino alla coda. Agitando in fretta le zampe, agitano pure quella
membrana e spiccano la volata, ma come dissi, non si reggono per
più di sessanta od ottanta metri.
— E ve ne sono in quest’isola?
— Ne ho vedute molte nel porto di Dori e nei boschi della baia di
Geelwinc.
— Taci!
— Ancora?
— Ma questa non è una scimmia volante.
Tesero gli orecchi rattenendo il respiro e udirono, verso l’alto corso
del fiume, un tonfo che pareva prodotto dalla caduta di un corpo
pesante. Guardarono in quella direzione, ma l’ombra dei boschi era
così cupa che non riuscirono a distinguere nulla.
— Hai udito, Horn?
— Sì, signor Cornelio, rispose il marinaio, che era diventato inquieto.
— Che qualcuno si sia tuffato nel fiume?
— Lo temo.
— Qualche pirata forse?
— Ma i pirati devono venire dalla parte della foce.
— È vero, ma possono aver preso terra per sorprenderci d’ambe le
parti.
Wan-Horn non rispose, ma crollò il capo come non prestasse fede.
— Cosa facciamo? chiese Cornelio, dopo alcuni istanti di silenzio.
— Sorvegliamo le acque, per ora. Se è un uomo, bisognerà che salga
sul banco di sabbia per giungere fino a noi e si scoprirà, non
essendoci acqua intorno a noi.
— È vero... to’!... un altro tonfo!...
— Ed un altro più lontano.
— Che siamo circondati?...
— Oh!... esclamò il marinaio. Guardate laggiù!...
Cornelio guardò nella direzione indicata e distinse, a fior d’acqua,
delle masse nerastre, assai lunghe, che s’avvicinavano lentamente
verso il banco di sabbia facendo gorgogliare la corrente.
— Dei canotti? chiese egli, alzandosi.
— O dei coccodrilli? disse il marinaio.
— Ve ne sono qui?...
— Su tutti i fiumi.
— Che vogliano assalirci?... Fortunatamente siamo sulla scialuppa.
— Ma arenati in mezzo ad un banco, signor Cornelio, e nell’assoluta
impossibilità di fuggire verso le sponde. Se giungono qui, non
avranno difficoltà a entrare nella scialuppa e fors’anche a sfondarla
colle loro formidabili code.
— Svegliamo mio zio, Horn.
— Tutti, signor Cornelio; stiamo per passare un brutto quarto d’ora.
Il capitano ed i suoi compagni furono tosto svegliati e messi al fatto
di ciò che stava per accadere.
— La faccenda può diventare grave, disse Wan-Stael. I coccodrilli dei
fiumi della Nuova Guinea sono feroci, e non temono l’uomo.
Comincia a salire la marea?
— Da un quarto d’ora, rispose Wan-Horn.
— Bisogna difenderci finchè ci rimetterà a galla.
— Ed i pirati non udranno le fucilate?
— Senza dubbio, Horn, e saliranno il fiume, ma non possiamo
lasciarci divorare per evitare il loro ritorno. Appena potremo
muoverci, ci salveremo nei boschi. Attenti che i coccodrilli arrivano, e
badate a scaricare le armi nelle loro gole o le palle si schiaccieranno
sulle loro robuste scaglie.
I coccodrilli infatti giungevano, ma non erano due o tre, ma una vera
banda, trenta, quaranta e forse di più. Come si erano radunati colà
tanti sauriani, mentre i naufraghi non ne avevano veduto nemmeno
uno durante il giorno? Provenivano forse da qualche grande palude o
da qualche lago situato più oltre, verso la sorgente di quel corso
d’acqua? Era probabile.
Quegli spaventevoli anfibi, accortisi della presenza di grosse prede,
giungevano da tutte le parti, circondando il banco.
Alla luce degli astri si scorgevano le loro enormi mascelle irte di
lunghi denti, le quali si richiudevano con un fracasso analogo a
quello che produce un cassone quando viene lasciato cadere il
coperchio.
Le loro code sferzavano l’acqua con impeto irresistibile, sollevando
delle vere ondate, e nell’urtarsi si udivano le scaglie risuonare come
piastre d’osso vuote.
Circondato il banco, s’arrestarono, come se volessero prima
assicurarsi di che specie era la preda che stavano per assalire, poi
uno, il più audace ed il più lungo, poichè misurava almeno nove
metri, con un poderoso colpo di coda si issò sul banco che la marea
a poco a poco copriva e marciò dritto verso la scialuppa.
— È orribile! esclamò Hans rabbrividendo.
— Coraggio, ragazzi! disse il capitano, che non perdeva la sua calma.
Questo è mio.
Il sauriano non era che a sei passi: con un colpo di coda poteva
lanciarsi contro la scialuppa.
Wan-Stael puntò freddamente il fucile e fece fuoco fra le mascelle
spalancate del mostro.
Questi, colpito a morte dalla palla che doveva avergli attraversato il
corpo dalla gola alla coda, si raddrizzò come un cavallo che
s’impenna, vibrando uno spaventevole colpo di coda, poi ricadde,
contorcendosi furiosamente, sollevando dei larghi sprazzi di fango.
Gli altri, lungi dallo spaventarsi alla detonazione che per loro doveva
riuscire nuova, non adoperando i papuasi armi da fuoco, nè per la
morte del loro compagno, balzarono sul banco precipitandosi verso
la scialuppa.
— Coraggio! ripetè un’ultima volta il capitano, che caricava
precipitosamente il fucile.
L’assalto fu tremendo. Quei formidabili sauriani, credendo forse che
anche la scialuppa fosse una preda da inghiottire, si arrampicavano
l’un sull’altro per giungere primi ad afferrare i bordi. I loro aliti caldi e
fetenti giungevano fino in volto ai disgraziati naufraghi.
Questi però, malgrado fossero terrorizzati, non erano rimasti
inoperosi. Scaricate le armi sui più vicini, avevano afferrate le scuri, i
ramponi e perfino i remi e si difendevano con sovrumana energia,
picchiando furiosamente sui crani e sulle mascelle, spezzando i denti
o lacerando le gole di quei mostri.
Fortunatamente la scialuppa era alta di bordo ed i coccodrilli non
potevano superarla e rovesciarsi nell’interno, ma cercavano di
riuscirvi colle code o di sfasciarla tentando di azzannarla. Wan-Horn
e il capitano, armati di scure, non li lasciavano avvicinarsi troppo, e
ogni testa che appariva sui bordi ricadeva fracassata, mentre Hans e
Cornelio, ritti sui banchi, avevano riprese le armi, scaricandole in
quelle enormi gole.
Quella difesa accanita, quelle detonazioni, quei lampi, quelle grida
parvero sconcertare gli assalitori, i quali si decisero a retrocedere
verso i margini del banco, ma senza abbandonarlo però.
Cinque di loro giacevano distesi sulla sabbia e altri tre, feriti
gravemente, fors’anche mortalmente, si dibattevano in preda a
spaventevoli convulsioni.
I naufraghi, ripresi i fucili, avevano ricominciato il fuoco. Incoraggiati
dal primo successo, cercavano ora di respingere nel fiume i sauriani,
i quali, invece, parevano più propensi a rinnovare l’assalto.
— Non perdete colpo, disse il capitano. Se possiamo resistere ancora
dieci minuti, la scialuppa lascerà il banco.
— È già tutto coperto, disse Cornelio. La marea monta rapidamente.
— Ma quei coccodrilli non si decidono ad andarsene, disse Wan-
Horn. Ecco un altro che torna all’assalto.
— A voi, ragazzi! gridò il capitano.
Due spari echeggiarono formando quasi una sola detonazione. Il
sauriano fece uno scarto che lo portò sull’orlo del banco, poi rotolò
nel fiume scomparendo sott’acqua.
Gli altri, che parevano indecisi, retrocessero, ma poi tornarono
all’assalto urtandosi e accavallandosi confusamente, decisi a finirla
colle prede umane. Già stavano per raggiungere la scialuppa quando
questa, che da qualche istante subiva delle oscillazioni, sollevata
dalla marea, si spostò fuggendo attraverso al banco.
— Galleggiamo! gridò Cornelio.
— Ai remi, Horn! gridò il capitano, scaricando il suo fucile in mezzo
alla banda di coccodrilli.
Il marinaio, il chinese ed Hans afferrarono i remi e si misero ad
arrancare disperatamente, dirigendo la scialuppa verso la sponda
sinistra, mentre Cornelio ed il capitano, con frequenti fucilate,
tenevano lontani i sauriani, i quali scoraggiati, non parevano più
risoluti a continuare l’assalto.
In pochi istanti la scialuppa attraversò il fiume e si arenò sulla riva,
in mezzo ad un gigantesco mazzo di erbe acquatiche.
Stavano per sbarcare, quando verso il basso corso del fiume udirono
delle voci umane ed uno sbattere di remi.
— Chi s’avvicina? chiese il capitano.
— I pirati senza dubbio, disse Wan-Horn. Hanno udito i nostri spari e
accorrono per assalirci.
— Dopo i coccodrilli i pirati! esclamò Cornelio. Che brutto paese e
che brutta notte!
— Tacete, disse il capitano.
Si curvò verso l’acqua e tese gli orecchi.
— Sì, diss’egli, dopo alcuni istanti. Devono essere pirati che salgono
il fiume. Ho udito lo sbattere di molti remi.
— Che salgano colle piroghe?
— Forse le hanno sciolte per renderle più leggiere e private dei ponti
e delle tettoie. Nascondiamo la scialuppa e salviamoci nei boschi.
CAPO XVI.
La capanna aerea
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
textbookfull.com