Rename samples to smoke tests

Closes gh-17197
pull/17322/head
Madhura Bhave 5 years ago
parent 0b720b99b2
commit d5c0009c6e

@ -125,7 +125,7 @@ find the process a little slower than the standard build.
[TIP]
====
If you want to run a build without the samples and integration tests, building the
If you want to run a build without the smoke tests and integration tests, building the
`spring-boot-project` module is enough. You can cd there and run the same command, or you
can run this from the top-level directory:
@ -196,7 +196,7 @@ changes just won't be automatically formatted.
With the requisite eclipse plugins installed you can select
`import existing maven projects` from the `file` menu to import the code. You will
need to import the root `spring-boot` pom and the `spring-boot-samples` pom separately.
need to import the root `spring-boot` pom and the `spring-boot-smoke-tests` pom separately.
@ -241,11 +241,11 @@ Maven is well supported by most Java IDEs. Refer to your vendor documentation.
== Integration Tests
The sample applications are used as integration tests during the build (when you
`./mvnw install`). Due to the fact that they make use of the `spring-boot-maven-plugin`
The smoke tests run as part of the build when you `./mvnw install`.
Due to the fact that they make use of the `spring-boot-maven-plugin`
they cannot be called directly, and so instead are launched via the
`maven-invoker-plugin`. If you encounter build failures running the integration tests,
check the `build.log` file in the appropriate sample directory.
check the `build.log` file in the appropriate smoke test directory.
== Cloning the git repository on Windows

@ -251,9 +251,6 @@ Groovy samples for use with the command line application are available in
link:spring-boot-project/spring-boot-cli/samples[spring-boot-cli/samples]. To run the CLI samples type
`spring run <sample>.groovy` from samples directory.
Java samples are available in link:spring-boot-samples[spring-boot-samples] and should
be built with maven and run by invoking `java -jar target/<sample>.jar`.
== Guides

@ -5,5 +5,5 @@ source $(dirname $0)/common.sh
repository=$(pwd)/distribution-repository
pushd git-repo > /dev/null
run_maven -f spring-boot-samples/pom.xml clean install -U -Dfull -Drepository=file://${repository}
run_maven -f spring-boot-smoke-tests/pom.xml clean install -U -Dfull -Drepository=file://${repository}
popd > /dev/null

@ -36,7 +36,7 @@ git commit -m"Release v$stageVersion" > /dev/null
git tag -a "v$stageVersion" -m"Release v$stageVersion" > /dev/null
run_maven -f spring-boot-project/pom.xml clean deploy -U -Dfull -DaltDeploymentRepository=distribution::default::file://${repository}
run_maven -f spring-boot-samples/pom.xml clean install -U -Dfull -Drepository=file://${repository}
run_maven -f spring-boot-smoke-tests/pom.xml clean install -U -Dfull -Drepository=file://${repository}
run_maven -f spring-boot-tests/spring-boot-integration-tests/pom.xml clean install -U -Dfull -Drepository=file://${repository}
run_maven -f spring-boot-tests/spring-boot-deployment-tests/pom.xml clean install -U -Dfull -Drepository=file://${repository}

@ -127,10 +127,10 @@
pattern="spring-boot-starter(s|-.*)"/>
</workingSet>
<workingSet
name="spring-boot-samples">
name="spring-boot-smoke-tests">
<predicate
xsi:type="predicates:NamePredicate"
pattern="spring-boot-sample(s|-.*)"/>
pattern="spring-boot-smoke-test(s|-.*)"/>
</workingSet>
<workingSet
name="spring-boot-tests">

@ -106,8 +106,8 @@
</build>
<modules>
<module>spring-boot-project</module>
<!-- Samples are built via the invoker plugin -->
<module>spring-boot-samples-invoker</module>
<!-- Smoke tests are built via the invoker plugin -->
<module>spring-boot-smoke-tests-invoker</module>
<module>spring-boot-tests</module>
</modules>
</profile>
@ -121,7 +121,7 @@
</activation>
<modules>
<module>spring-boot-project</module>
<module>spring-boot-samples</module>
<module>spring-boot-smoke-tests</module>
<module>spring-boot-tests</module>
</modules>
</profile>

@ -557,7 +557,7 @@ editor for this example.
[[getting-started-first-application-dependencies]]
=== Adding Classpath Dependencies
Spring Boot provides a number of "`Starters`" that let you add jars to your classpath.
Our sample application has already used `spring-boot-starter-parent` in the `parent`
Our applications for smoke tests use the `spring-boot-starter-parent` in the `parent`
section of the POM. The `spring-boot-starter-parent` is a special starter that provides
useful Maven defaults. It also provides a
<<using-spring-boot.adoc#using-boot-dependency-management,`dependency-management`>>
@ -819,11 +819,6 @@ https://spring.io/guides/[getting started] guides that solve specific "`How do I
with Spring?`" problems. We also have Spring Boot-specific
"`<<howto.adoc#howto, How-to>>`" reference documentation.
The https://github.com/{github-repo}[Spring Boot repository] also has a
{github-code}/spring-boot-samples[bunch of samples] you can run. The samples are
independent of the rest of the code (that is, you do not need to build the rest to run or
use the samples).
Otherwise, the next logical step is to read _<<using-spring-boot.adoc#using-boot>>_. If
you are really impatient, you could also jump ahead and read about
_<<spring-boot-features.adoc#boot-features, Spring Boot features>>_.

@ -699,9 +699,7 @@ a plain HTTP connector at port 8080. Spring Boot does not support the configurat
both an HTTP connector and an HTTPS connector through `application.properties`. If you
want to have both, you need to configure one of them programmatically. We recommend using
`application.properties` to configure HTTPS, as the HTTP connector is the easier of the
two to configure programmatically. See the
{github-code}/spring-boot-samples/spring-boot-sample-tomcat-multi-connectors[`spring-boot-sample-tomcat-multi-connectors`]
sample project for an example.
two to configure programmatically.
@ -1668,9 +1666,7 @@ And the following example shows one way to set up the starters in Gradle:
NOTE: The Log4j starters gather together the dependencies for common logging
requirements (such as having Tomcat use `java.util.logging` but configuring the
output using Log4j 2). See the
{github-code}/spring-boot-samples/spring-boot-sample-actuator-log4j2[Actuator Log4j 2]
samples for more detail and to see it in action.
output using Log4j 2).
NOTE: To ensure that debug logging performed using `java.util.logging` is routed into
Log4j 2, configure its https://logging.apache.org/log4j/2.0/log4j-jul/index.html[JDK
@ -1895,9 +1891,7 @@ the same package (or a sub-package) of your `@EnableAutoConfiguration` class.
For many applications, all you need is to put the right Spring Data dependencies on
your classpath (there is a `spring-boot-starter-data-jpa` for JPA and a
`spring-boot-starter-data-mongodb` for Mongodb) and create some repository interfaces to
handle your `@Entity` objects. Examples are in the
{github-code}/spring-boot-samples/spring-boot-sample-data-jpa[JPA sample] and the
{github-code}/spring-boot-samples/spring-boot-sample-data-mongodb[Mongodb sample].
handle your `@Entity` objects.
Spring Boot tries to guess the location of your `@Repository` definitions, based on the
`@EnableAutoConfiguration` it finds. To get more control, use the `@EnableJpaRepositories`
@ -2356,8 +2350,6 @@ is sufficient to cause Flyway to use its own `DataSource`. If any of the three
properties has not be set, the value of its equivalent `spring.datasource` property will
be used.
There is a {github-code}/spring-boot-samples/spring-boot-sample-flyway[Flyway sample] so
that you can see how to set things up.
You can also use Flyway to provide data for specific scenarios. For example, you can
place test-specific migrations in `src/test/resources` and they are run only when your
@ -2399,9 +2391,6 @@ See
{sc-spring-boot-autoconfigure}/liquibase/LiquibaseProperties.{sc-ext}[`LiquibaseProperties`]
for details about available settings such as contexts, the default schema, and others.
There is a {github-code}/spring-boot-samples/spring-boot-sample-liquibase[Liquibase
sample] so that you can see how to set things up.
[[howto-messaging]]
@ -3049,22 +3038,6 @@ The following example shows how to build an executable archive with Ant:
</target>
----
The {github-code}/spring-boot-samples/spring-boot-sample-ant[Ant Sample] has a
`build.xml` file with a `manual` task that should work if you run it with the following
command:
[indent=0,subs="verbatim,quotes,attributes"]
----
$ ant -lib <folder containing ivy-2.2.jar> clean manual
----
Then you can run the application with the following command:
[indent=0,subs="verbatim,quotes,attributes"]
----
$ java -jar target/*.jar
----
[[howto-traditional-deployment]]
@ -3166,11 +3139,6 @@ file with the provided dependencies packaged in a `lib-provided` directory. This
that, in addition to being deployable to a servlet container, you can also run your
application by using `java -jar` on the command line.
TIP: Take a look at Spring Boot's sample applications for a
{github-code}/spring-boot-samples/spring-boot-sample-traditional/pom.xml[Maven-based
example] of the previously described configuration.
[[howto-convert-an-existing-application-to-spring-boot]]

@ -1586,9 +1586,7 @@ You can also add a custom Spring `Validator` by creating a bean definition calle
configuration properties validator is created very early in the application's lifecycle,
and declaring the `@Bean` method as static lets the bean be created without having to
instantiate the `@Configuration` class. Doing so avoids any problems that may be caused
by early instantiation. There is a
{github-code}/spring-boot-samples/spring-boot-sample-property-validation[property
validation sample] that shows how to set things up.
by early instantiation.
TIP: The `spring-boot-actuator` module includes an endpoint that exposes all
`@ConfigurationProperties` beans. Point your web browser to
@ -3212,9 +3210,6 @@ an `@Order`, which you can set with `spring.jersey.filter.order`. Both the servl
the filter registrations can be given init parameters by using `spring.jersey.init.*` to
specify a map of properties.
There is a {github-code}/spring-boot-samples/spring-boot-sample-jersey[Jersey sample] so
that you can see how to set things up.
[[boot-features-embedded-container]]
@ -3422,9 +3417,6 @@ packaged as an executable archive), there are some limitations in the JSP suppor
<<boot-features-error-handling-custom-error-pages,Custom error pages>> should be used
instead.
There is a {github-code}/spring-boot-samples/spring-boot-sample-web-jsp[JSP sample] so
that you can see how to set things up.
[[boot-features-reactive-server]]
@ -3646,8 +3638,6 @@ so does not disable the `UserDetailsService` configuration or Actuator's securit
To also switch off the `UserDetailsService` configuration, you can add a bean of type
`UserDetailsService`, `AuthenticationProvider`, or `AuthenticationManager`.
There are several secure applications in the {github-code}/spring-boot-samples/[Spring
Boot samples] to get you started with common use cases.
Access rules can be overridden by adding a custom `WebSecurityConfigurerAdapter`. Spring
Boot provides convenience methods that can be used to override access rules for actuator

@ -1,81 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-parent</artifactId>
<version>${revision}</version>
<relativePath>../spring-boot-project/spring-boot-parent</relativePath>
</parent>
<artifactId>spring-boot-samples-invoker</artifactId>
<packaging>pom</packaging>
<name>Spring Boot Samples Invoker</name>
<description>Spring Boot Samples Invoker</description>
<properties>
<main.basedir>${basedir}/..</main.basedir>
</properties>
<build>
<plugins>
<plugin>
<!-- We use invoker so that the spring-boot-maven-plugin can be used -->
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-invoker-plugin</artifactId>
<inherited>false</inherited>
<configuration>
<projectsDirectory>${main.basedir}/spring-boot-samples</projectsDirectory>
<skipInvocation>${skipTests}</skipInvocation>
<streamLogs>true</streamLogs>
<pomIncludes>
<pomInclude>pom.xml</pomInclude>
</pomIncludes>
</configuration>
<executions>
<execution>
<id>integration-test</id>
<phase>install</phase>
<goals>
<goal>run</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-antrun-plugin</artifactId>
<inherited>false</inherited>
<executions>
<execution>
<id>clean-samples</id>
<phase>clean</phase>
<goals>
<goal>run</goal>
</goals>
<configuration>
<target>
<delete includeemptydirs="true">
<fileset dir="${main.basedir}/spring-boot-samples"
includes="**/target/" />
</delete>
</target>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-clean-plugin</artifactId>
<inherited>false</inherited>
<executions>
<execution>
<id>clean-samples</id>
<phase>clean</phase>
<goals>
<goal>clean</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

@ -1,244 +0,0 @@
= Spring Boot Samples
The following sample applications are provided:
|===
| Sample | Description
| link:spring-boot-sample-activemq[spring-boot-sample-activemq]
| JMS consumer and producer using Apache ActiveMQ
| link:spring-boot-sample-actuator[spring-boot-sample-actuator]
| REST service with production-ready features
| link:spring-boot-sample-actuator-log4j2[spring-boot-sample-actuator-log4j2]
| Production-ready features using log4j 2 for logging (instead of logback)
| link:spring-boot-sample-actuator-noweb[spring-boot-sample-actuator-noweb]
| Non-web application with production-ready features
| link:spring-boot-sample-actuator-ui[spring-boot-sample-actuator-ui]
| Web UI example with production-ready features
| link:spring-boot-sample-amqp[spring-boot-sample-amqp]
| Message-oriented application using AMQP and RabbitMQ
| link:spring-boot-sample-ant[spring-boot-sample-ant]
| Executable JAR build using Ant
| link:spring-boot-sample-aop[spring-boot-sample-aop]
| Demonstrates explicit usage of Spring AOP
| link:spring-boot-sample-atmosphere[spring-boot-sample-atmosphere]
| Chat service built using Atmosphere
| link:spring-boot-sample-batch[spring-boot-sample-batch]
| Define and run a Batch job in a few lines of code
| link:spring-boot-sample-cache[spring-boot-sample-cache]
| Web application that uses Spring's cache abstraction
| link:spring-boot-sample-custom-layout[spring-boot-sample-custom-layout]
| Creates custom Jar Layout
| link:spring-boot-sample-data-cassandra[spring-boot-sample-data-cassandra]
| Stores data using Spring Data Cassandra
| link:spring-boot-sample-data-couchbase[spring-boot-sample-data-couchbase]
| Stores data using Spring Data Couchbase
| link:spring-boot-sample-data-elasticsearch[spring-boot-sample-data-elasticsearch]
| Stores data using Spring Data Elasticsearch
| link:spring-boot-sample-data-jdbc[spring-boot-sample-data-jdbc]
| Stores data using Spring Data JDBC
| link:spring-boot-sample-data-jpa[spring-boot-sample-data-jpa]
| Stores data using Spring Data JPA with Hibernate
| link:spring-boot-sample-data-ldap[spring-boot-sample-data-ldap]
| Stores data using Spring Data LDAP
| link:spring-boot-sample-data-mongodb[spring-boot-sample-data-mongodb]
| Stores data using Spring Data MongoDB
| link:spring-boot-sample-data-neo4j[spring-boot-sample-data-neo4j]
| Stores data using Spring Data Neo4j
| link:spring-boot-sample-data-redis[spring-boot-sample-data-redis]
| Stores data using Spring Data Redis
| link:spring-boot-sample-data-rest[spring-boot-sample-data-rest]
| RESTful service built using Spring Data REST
| link:spring-boot-sample-data-solr[spring-boot-sample-data-solr]
| Stores data using Spring Data Solr
| link:spring-boot-sample-devtools[spring-boot-sample-devtools]
| Using DevTools for rapid application development
| link:spring-boot-sample-flyway[spring-boot-sample-flyway]
| Database migrations with Flyway
| link:spring-boot-sample-hateoas[spring-boot-sample-hateoas]
| RESTful API built using Spring Hateoas
| link:spring-boot-sample-integration[spring-boot-sample-integration]
| Integration application built using Spring Integration and its Java DSL
| link:spring-boot-sample-jersey[spring-boot-sample-jersey]
| RESTful service built using Jersey
| link:spring-boot-sample-jetty[spring-boot-sample-jetty]
| Embedded Jetty
| link:spring-boot-sample-jetty-ssl[spring-boot-sample-jetty-ssl]
| Embedded Jetty configured to use SSL
| link:spring-boot-sample-jetty-jsp[spring-boot-sample-jetty-jsp]
| Web application that uses JSP templates with Jetty
| link:spring-boot-sample-jooq[spring-boot-sample-jooq]
| Stores data using jOOQ
| link:spring-boot-sample-jpa[spring-boot-sample-jpa]
| Uses plain JPA (Hibernate)
| link:spring-boot-sample-jta-atomikos[spring-boot-sample-jta-atomikos]
| JTA transactions with Atomikos
| link:spring-boot-sample-jta-bitronix[spring-boot-sample-jta-bitronix]
| JTA transactions with Bitronix
| link:spring-boot-sample-jta-jndi[spring-boot-sample-jta-jndi]
| JTA transactions using a `TransactionManager` and `DataSource` from JNDI
| link:spring-boot-sample-junit-jupiter[spring-boot-sample-junit-jupiter]
| Demonstrates JUnit Jupiter-based testing
| link:spring-boot-sample-kafka[spring-boot-sample-kafka]
| Consumer and producer using Apache Kafka
| link:spring-boot-sample-liquibase[spring-boot-sample-liquibase]
| Database migrations with Liquibase
| link:spring-boot-sample-logback[spring-boot-sample-logback]
| Demonstrates Spring Boot's custom Logback functionality configured in logback-spring.xml
| link:spring-boot-sample-metrics-dropwizard[spring-boot-sample-metrics-dropwizard]
| Demonstrates support for Dropwizard metrics
| link:spring-boot-sample-metrics-opentsdb[spring-boot-sample-metrics-opentsdb]
| Exports metrics to OpenTSDB
| link:spring-boot-sample-metrics-redis[spring-boot-sample-metrics-redis]
| Exports metrics to Redis
| link:spring-boot-sample-oauth2-client[spring-boot-sample-oauth2-client]
| Configure an OAuth2 login client
| link:spring-boot-sample-reactive-oauth2-client[spring-boot-sample-reactive-oauth2-client]
| Configure a Reactive OAuth2 login client
| link:spring-boot-sample-oauth2-resource-server[spring-boot-sample-oauth2-resource-server]
| Configure an OAuth2 resource server
| link:spring-boot-sample-reactive-oauth2-resource-server[spring-boot-sample-reactive-oauth2-resource-server]
| Configure a Reactive OAuth2 resource server
| link:spring-boot-sample-parent-context[spring-boot-sample-parent-context]
| Application that uses an `ApplicationContext` with a parent
| link:spring-boot-sample-profile[spring-boot-sample-profile]
| Demonstrates some of Spring Framework's `@Profile` capabilities
| link:spring-boot-sample-property-validation[spring-boot-sample-property-validation]
| Demonstrates the usage of `@ConfigurationProperties` with a Spring `Validator`
| link:spring-boot-sample-secure[spring-boot-sample-secure]
| Non-web application that uses Spring Security
| link:spring-boot-sample-servlet[spring-boot-sample-servlet]
| Web application with a "raw" `Servlet` returning plain text content
| link:spring-boot-sample-session[spring-boot-sample-session]
| Web Application that uses Spring Session to manage session data
| link:spring-boot-sample-simple[spring-boot-sample-simple]
| Simple command line application
| link:spring-boot-sample-test[spring-boot-sample-test]
| Demonstrates Spring Boot's testing capabilities
| link:spring-boot-sample-testng[spring-boot-sample-testng]
| Demonstrates TestNG-based testing
| link:spring-boot-sample-tomcat[spring-boot-sample-tomcat]
| Embedded Tomcat
| link:spring-boot-sample-tomcat-jsp[spring-boot-sample-tomcat-jsp]
| Web application that uses JSP templates with Tomcat
| link:spring-boot-sample-tomcat-multi-connectors[spring-boot-sample-tomcat-multi-connectors]
| Web application that uses Tomcat configured with multiple connectors
| link:spring-boot-sample-tomcat-ssl[spring-boot-sample-tomcat-ssl]
| Web application that uses Tomcat configured with SSL
| link:spring-boot-sample-traditional[spring-boot-sample-traditional]
| Traditional WAR packaging (but also executable using `java -jar`)
| link:spring-boot-sample-undertow[spring-boot-sample-undertow]
| Embedded Undertow
| link:spring-boot-sample-undertow-ssl[spring-boot-sample-undertow-ssl]
| Embedded Undertow configured to use SSL
| link:spring-boot-sample-war[spring-boot-sample-war]
| Web application packaged as a war file
| link:spring-boot-sample-web-freemarker[spring-boot-sample-web-freemarker]
| Web application that uses FreeMarker templates
| link:spring-boot-sample-web-groovy-templates[spring-boot-sample-web-groovy-templates]
| Web application that uses Groovy templates
| link:spring-boot-sample-web-jsp[spring-boot-sample-web-jsp]
| Web application that uses JSP templates
| link:spring-boot-sample-web-method-security[spring-boot-sample-web-method-security]
| Web application with Security configuration enabling global method security
| link:spring-boot-sample-web-mustache[spring-boot-sample-web-mustache]
| Web application that uses Mustache views
| link:spring-boot-sample-web-secure[spring-boot-sample-web-secure]
| Web application with typical Security configuration enabling a login form
| link:spring-boot-sample-web-secure-custom[spring-boot-sample-web-secure-custom]
| Web application with custom Spring Security configuration
| link:spring-boot-sample-web-secure-jdbc[spring-boot-sample-web-secure-jdbc]
| Web application with Spring Security configured to use JDBC authentication
| link:spring-boot-sample-web-static[spring-boot-sample-web-static]
| Web application that serves static files
| link:spring-boot-sample-web-ui[spring-boot-sample-web-ui]
| Web application with a basic UI built using Bootstrap and JQuery
| link:spring-boot-sample-webservices[spring-boot-sample-webservices]
| Simple contract-first SOAP web service with Spring Web Services
| link:spring-boot-sample-websocket-jetty[spring-boot-sample-websocket-jetty]
| WebSocket application that uses Jetty
| link:spring-boot-sample-websocket-tomcat[spring-boot-sample-websocket-tomcat]
| WebSocket application that uses Tomcat
| link:spring-boot-sample-websocket-undertow[spring-boot-sample-websocket-undertow]
| WebSocket application that uses Undertow
| link:spring-boot-sample-xml[spring-boot-sample-xml]
| Example show how Spring Boot can be mixed with traditional XML configuration (we
generally recommend using Java `@Configuration` whenever possible

@ -1,250 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>${revision}</version>
<relativePath>../spring-boot-project/spring-boot-starters/spring-boot-starter-parent</relativePath>
</parent>
<artifactId>spring-boot-samples</artifactId>
<packaging>pom</packaging>
<name>Spring Boot Samples</name>
<description>Spring Boot Samples</description>
<properties>
<main.basedir>${basedir}/..</main.basedir>
<java.version>1.8</java.version>
<disable.checks>false</disable.checks>
</properties>
<modules>
<module>spring-boot-sample-ant</module>
<module>spring-boot-sample-activemq</module>
<module>spring-boot-sample-actuator</module>
<module>spring-boot-sample-actuator-log4j2</module>
<module>spring-boot-sample-actuator-noweb</module>
<module>spring-boot-sample-actuator-ui</module>
<module>spring-boot-sample-actuator-custom-security</module>
<module>spring-boot-sample-amqp</module>
<module>spring-boot-sample-animated-banner</module>
<module>spring-boot-sample-aop</module>
<module>spring-boot-sample-atmosphere</module>
<module>spring-boot-sample-batch</module>
<module>spring-boot-sample-cache</module>
<module>spring-boot-sample-custom-layout</module>
<module>spring-boot-sample-data-cassandra</module>
<module>spring-boot-sample-data-couchbase</module>
<module>spring-boot-sample-data-elasticsearch</module>
<module>spring-boot-sample-data-jdbc</module>
<module>spring-boot-sample-data-jpa</module>
<module>spring-boot-sample-data-ldap</module>
<module>spring-boot-sample-data-mongodb</module>
<module>spring-boot-sample-data-neo4j</module>
<module>spring-boot-sample-data-redis</module>
<module>spring-boot-sample-data-rest</module>
<module>spring-boot-sample-data-solr</module>
<module>spring-boot-sample-devtools</module>
<module>spring-boot-sample-flyway</module>
<module>spring-boot-sample-hateoas</module>
<module>spring-boot-sample-integration</module>
<module>spring-boot-sample-jersey</module>
<module>spring-boot-sample-jetty</module>
<module>spring-boot-sample-jetty-jsp</module>
<module>spring-boot-sample-jetty-ssl</module>
<module>spring-boot-sample-jooq</module>
<module>spring-boot-sample-jpa</module>
<module>spring-boot-sample-jta-atomikos</module>
<module>spring-boot-sample-jta-bitronix</module>
<module>spring-boot-sample-jta-jndi</module>
<module>spring-boot-sample-junit-jupiter</module>
<module>spring-boot-sample-junit-vintage</module>
<module>spring-boot-sample-kafka</module>
<module>spring-boot-sample-liquibase</module>
<module>spring-boot-sample-logback</module>
<module>spring-boot-sample-oauth2-client</module>
<module>spring-boot-sample-oauth2-resource-server</module>
<module>spring-boot-sample-parent-context</module>
<module>spring-boot-sample-profile</module>
<module>spring-boot-sample-property-validation</module>
<module>spring-boot-sample-quartz</module>
<module>spring-boot-sample-reactive-oauth2-client</module>
<module>spring-boot-sample-reactive-oauth2-resource-server</module>
<module>spring-boot-sample-secure</module>
<module>spring-boot-sample-secure-webflux</module>
<module>spring-boot-sample-servlet</module>
<module>spring-boot-sample-session</module>
<module>spring-boot-sample-session-webflux</module>
<module>spring-boot-sample-simple</module>
<module>spring-boot-sample-test</module>
<module>spring-boot-sample-test-nomockito</module>
<module>spring-boot-sample-testng</module>
<module>spring-boot-sample-tomcat</module>
<module>spring-boot-sample-tomcat-jsp</module>
<module>spring-boot-sample-tomcat-ssl</module>
<module>spring-boot-sample-tomcat-multi-connectors</module>
<module>spring-boot-sample-traditional</module>
<module>spring-boot-sample-undertow</module>
<module>spring-boot-sample-undertow-ssl</module>
<module>spring-boot-sample-war</module>
<module>spring-boot-sample-web-freemarker</module>
<module>spring-boot-sample-web-groovy-templates</module>
<module>spring-boot-sample-web-jsp</module>
<module>spring-boot-sample-web-method-security</module>
<module>spring-boot-sample-web-mustache</module>
<module>spring-boot-sample-web-secure</module>
<module>spring-boot-sample-web-secure-custom</module>
<module>spring-boot-sample-web-secure-jdbc</module>
<module>spring-boot-sample-web-static</module>
<module>spring-boot-sample-web-ui</module>
<module>spring-boot-sample-webflux</module>
<module>spring-boot-sample-websocket-jetty</module>
<module>spring-boot-sample-websocket-tomcat</module>
<module>spring-boot-sample-websocket-undertow</module>
<module>spring-boot-sample-webservices</module>
<module>spring-boot-sample-xml</module>
</modules>
<!-- No dependencies - otherwise the samples won't work if you change the
parent -->
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>flatten-maven-plugin</artifactId>
<inherited>true</inherited>
<executions>
<execution>
<id>flatten</id>
<phase>process-resources</phase>
<goals>
<goal>flatten</goal>
</goals>
<configuration>
<updatePomFile>true</updatePomFile>
<flattenMode>oss</flattenMode>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.eclipse.m2e</groupId>
<artifactId>lifecycle-mapping</artifactId>
<version>1.0.0</version>
<configuration>
<lifecycleMappingMetadata>
<pluginExecutions>
<pluginExecution>
<pluginExecutionFilter>
<groupId>
org.apache.maven.plugins
</groupId>
<artifactId>
maven-enforcer-plugin
</artifactId>
<versionRange>
[1.3.1,)
</versionRange>
<goals>
<goal>enforce</goal>
</goals>
</pluginExecutionFilter>
<action>
<ignore />
</action>
</pluginExecution>
<pluginExecution>
<pluginExecutionFilter>
<groupId>
org.springframework.boot
</groupId>
<artifactId>
spring-boot-maven-plugin
</artifactId>
<versionRange>
[1.4.0.BUILD-SNAPSHOT,)
</versionRange>
<goals>
<goal>build-info</goal>
</goals>
</pluginExecutionFilter>
<action>
<ignore />
</action>
</pluginExecution>
</pluginExecutions>
</lifecycleMappingMetadata>
</configuration>
</plugin>
</plugins>
</pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<includes>
<include>**/*Tests.java</include>
</includes>
<excludes>
<exclude>**/Abstract*.java</exclude>
</excludes>
<systemPropertyVariables>
<java.security.egd>file:/dev/./urandom</java.security.egd>
<java.awt.headless>true</java.awt.headless>
</systemPropertyVariables>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-enforcer-plugin</artifactId>
<executions>
<execution>
<id>enforce-rules</id>
<goals>
<goal>enforce</goal>
</goals>
<configuration>
<rules>
<bannedDependencies>
<excludes>
<exclude>commons-logging:*:*</exclude>
</excludes>
<searchTransitive>true</searchTransitive>
</bannedDependencies>
</rules>
<fail>true</fail>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-install-plugin</artifactId>
<configuration>
<skip>true</skip>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<configuration>
<skip>true</skip>
</configuration>
<inherited>true</inherited>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>fast</id>
<activation>
<property>
<name>fast</name>
</property>
</activation>
<properties>
<disable.checks>true</disable.checks>
</properties>
</profile>
</profiles>
</project>

@ -1,38 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<!-- Your own application should inherit from spring-boot-starter-parent -->
<artifactId>spring-boot-samples</artifactId>
<groupId>org.springframework.boot</groupId>
<version>${revision}</version>
</parent>
<artifactId>spring-boot-sample-activemq</artifactId>
<name>Spring Boot ActiveMQ Sample</name>
<description>Spring Boot ActiveMQ Sample</description>
<properties>
<main.basedir>${basedir}/../..</main.basedir>
</properties>
<dependencies>
<!-- Compile -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-activemq</artifactId>
</dependency>
<!-- Test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

@ -1,30 +0,0 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.activemq;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;
@Component
public class Consumer {
@JmsListener(destination = "sample.queue")
public void receiveQueue(String text) {
System.out.println(text);
}
}

@ -1,45 +0,0 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.activemq;
import javax.jms.Queue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.stereotype.Component;
@Component
public class Producer implements CommandLineRunner {
@Autowired
private JmsMessagingTemplate jmsMessagingTemplate;
@Autowired
private Queue queue;
@Override
public void run(String... args) throws Exception {
send("Sample message");
System.out.println("Message was sent to the Queue");
}
public void send(String msg) {
this.jmsMessagingTemplate.convertAndSend(this.queue, msg);
}
}

@ -1,41 +0,0 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.activemq;
import javax.jms.Queue;
import org.apache.activemq.command.ActiveMQQueue;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.jms.annotation.EnableJms;
@SpringBootApplication
@EnableJms
public class SampleActiveMQApplication {
@Bean
public Queue queue() {
return new ActiveMQQueue("sample.queue");
}
public static void main(String[] args) {
SpringApplication.run(SampleActiveMQApplication.class, args);
}
}

@ -1,48 +0,0 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.activemq;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.system.CapturedOutput;
import org.springframework.boot.test.system.OutputCaptureExtension;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Integration tests for demo application.
*
* @author Eddú Meléndez
*/
@SpringBootTest
@ExtendWith(OutputCaptureExtension.class)
class SampleActiveMqTests {
@Autowired
private Producer producer;
@Test
void sendSimpleMessage(CapturedOutput capturedOutput) throws InterruptedException {
this.producer.send("Test message");
Thread.sleep(1000L);
assertThat(capturedOutput).contains("Test message");
}
}

@ -1,60 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<!-- Your own application should inherit from spring-boot-starter-parent -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-samples</artifactId>
<version>${revision}</version>
</parent>
<artifactId>spring-boot-sample-actuator-custom-security</artifactId>
<name>Spring Boot Actuator Custom Security Sample</name>
<description>Spring Boot Actuator Custom Security Sample</description>
<properties>
<main.basedir>${basedir}/../..</main.basedir>
</properties>
<dependencies>
<!-- Compile -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.jolokia</groupId>
<artifactId>jolokia-core</artifactId>
</dependency>
<!-- Runtime -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<scope>runtime</scope>
</dependency>
<!-- Test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

@ -1,42 +0,0 @@
/*
* Copyright 2012-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.actuator.customsecurity;
import java.util.Date;
import java.util.Map;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class ExampleController {
@GetMapping("/")
public String home(Map<String, Object> model) {
model.put("message", "Hello World");
model.put("title", "Hello Home");
model.put("date", new Date());
return "home";
}
@RequestMapping("/foo")
public String foo() {
throw new RuntimeException("Expected exception in controller");
}
}

@ -1,34 +0,0 @@
/*
* Copyright 2012-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.actuator.customsecurity;
import org.springframework.boot.actuate.endpoint.web.annotation.RestControllerEndpoint;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Component
@RestControllerEndpoint(id = "example")
public class ExampleRestControllerEndpoint {
@GetMapping("/echo")
public ResponseEntity<String> echo(@RequestParam("text") String text) {
return ResponseEntity.ok().header("echo", text).body(text);
}
}

@ -1,29 +0,0 @@
/*
* Copyright 2012-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.actuator.customsecurity;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SampleActuatorCustomSecurityApplication {
public static void main(String[] args) {
SpringApplication.run(SampleActuatorCustomSecurityApplication.class, args);
}
}

@ -1,60 +0,0 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.actuator.customsecurity;
import org.springframework.boot.actuate.autoconfigure.security.servlet.EndpointRequest;
import org.springframework.boot.actuate.web.mappings.MappingsEndpoint;
import org.springframework.boot.autoconfigure.security.servlet.PathRequest;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
@Configuration(proxyBeanMethods = false)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@SuppressWarnings("deprecation")
@Bean
public InMemoryUserDetailsManager inMemoryUserDetailsManager() {
return new InMemoryUserDetailsManager(
User.withDefaultPasswordEncoder().username("user").password("password").authorities("ROLE_USER")
.build(),
User.withDefaultPasswordEncoder().username("beans").password("beans").authorities("ROLE_BEANS").build(),
User.withDefaultPasswordEncoder().username("admin").password("admin")
.authorities("ROLE_ACTUATOR", "ROLE_USER").build());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http.authorizeRequests()
.mvcMatchers("/actuator/beans").hasRole("BEANS")
.requestMatchers(EndpointRequest.to("health", "info")).permitAll()
.requestMatchers(EndpointRequest.toAnyEndpoint().excluding(MappingsEndpoint.class)).hasRole("ACTUATOR")
.requestMatchers(PathRequest.toStaticResources().atCommonLocations()).permitAll()
.antMatchers("/foo").permitAll()
.antMatchers("/**").hasRole("USER")
.and()
.cors()
.and()
.httpBasic();
// @formatter:on
}
}

@ -1,83 +0,0 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.actuator.customsecurity;
import java.net.URI;
import java.util.Map;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.LocalHostUriTemplateHandler;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.ApplicationContext;
import org.springframework.http.HttpStatus;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.ActiveProfiles;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Integration test for cors preflight requests to management endpoints.
*
* @author Madhura Bhave
*/
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ActiveProfiles("cors")
class CorsSampleActuatorApplicationTests {
private TestRestTemplate testRestTemplate;
@Autowired
private ApplicationContext applicationContext;
@BeforeEach
void setUp() {
RestTemplateBuilder builder = new RestTemplateBuilder();
LocalHostUriTemplateHandler handler = new LocalHostUriTemplateHandler(this.applicationContext.getEnvironment(),
"http");
builder = builder.uriTemplateHandler(handler);
this.testRestTemplate = new TestRestTemplate(builder);
}
@Test
void endpointShouldReturnUnauthorized() {
ResponseEntity<?> entity = this.testRestTemplate.getForEntity("/actuator/env", Map.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
}
@Test
void preflightRequestToEndpointShouldReturnOk() throws Exception {
RequestEntity<?> healthRequest = RequestEntity.options(new URI("/actuator/env"))
.header("Origin", "http://localhost:8080").header("Access-Control-Request-Method", "GET").build();
ResponseEntity<?> exchange = this.testRestTemplate.exchange(healthRequest, Map.class);
assertThat(exchange.getStatusCode()).isEqualTo(HttpStatus.OK);
}
@Test
void preflightRequestWhenCorsConfigInvalidShouldReturnForbidden() throws Exception {
RequestEntity<?> entity = RequestEntity.options(new URI("/actuator/env"))
.header("Origin", "http://localhost:9095").header("Access-Control-Request-Method", "GET").build();
ResponseEntity<byte[]> exchange = this.testRestTemplate.exchange(entity, byte[].class);
assertThat(exchange.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN);
}
}

@ -1,85 +0,0 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.actuator.customsecurity;
import org.junit.jupiter.api.Test;
import org.springframework.boot.actuate.autoconfigure.web.server.LocalManagementPort;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Integration tests for separate management and main service ports.
*
* @author Dave Syer
* @author Madhura Bhave
*/
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT,
properties = { "management.server.port=0", "management.server.servlet.context-path=/management" })
class ManagementPortAndPathSampleActuatorApplicationTests {
@LocalServerPort
private int port;
@LocalManagementPort
private int managementPort;
@Test
void testHome() {
ResponseEntity<String> entity = new TestRestTemplate("user", "password")
.getForEntity("http://localhost:" + this.port, String.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(entity.getBody()).contains("Hello World");
}
@Test
void actuatorPathOnMainPortShouldNotMatch() {
ResponseEntity<String> entity = new TestRestTemplate()
.getForEntity("http://localhost:" + this.port + "/actuator/health", String.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
}
@Test
void testSecureActuator() {
ResponseEntity<String> entity = new TestRestTemplate()
.getForEntity("http://localhost:" + this.managementPort + "/management/actuator/env", String.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
}
@Test
void testInsecureActuator() {
ResponseEntity<String> entity = new TestRestTemplate()
.getForEntity("http://localhost:" + this.managementPort + "/management/actuator/health", String.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(entity.getBody()).contains("\"status\":\"UP\"");
}
@Test
void testMissing() {
ResponseEntity<String> entity = new TestRestTemplate("admin", "admin")
.getForEntity("http://localhost:" + this.managementPort + "/management/actuator/missing", String.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND);
assertThat(entity.getBody()).contains("\"status\":404");
}
}

@ -1,162 +0,0 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.actuator.customsecurity;
import java.util.Map;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.LocalHostUriTemplateHandler;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.core.env.Environment;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Madhura Bhave
* @author Stephane Nicoll
*/
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class SampleActuatorCustomSecurityApplicationTests {
@Autowired
private Environment environment;
@Test
void homeIsSecure() {
@SuppressWarnings("rawtypes")
ResponseEntity<Map> entity = restTemplate().getForEntity("/", Map.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
@SuppressWarnings("unchecked")
Map<String, Object> body = entity.getBody();
assertThat(body.get("error")).isEqualTo("Unauthorized");
assertThat(entity.getHeaders()).doesNotContainKey("Set-Cookie");
}
@Test
void testInsecureApplicationPath() {
@SuppressWarnings("rawtypes")
ResponseEntity<Map> entity = restTemplate().getForEntity("/foo", Map.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR);
@SuppressWarnings("unchecked")
Map<String, Object> body = entity.getBody();
assertThat((String) body.get("message")).contains("Expected exception in controller");
}
@Test
void testInsecureStaticResources() {
ResponseEntity<String> entity = restTemplate().getForEntity("/css/bootstrap.min.css", String.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(entity.getBody()).contains("body");
}
@Test
void actuatorInsecureEndpoint() {
ResponseEntity<String> entity = restTemplate().getForEntity("/actuator/health", String.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(entity.getBody()).contains("\"status\":\"UP\"");
}
@Test
void actuatorLinksIsSecure() {
ResponseEntity<Object> entity = restTemplate().getForEntity("/actuator", Object.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
entity = adminRestTemplate().getForEntity("/actuator", Object.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
}
@Test
void actuatorSecureEndpointWithAnonymous() {
ResponseEntity<Object> entity = restTemplate().getForEntity("/actuator/env", Object.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
}
@Test
void actuatorSecureEndpointWithUnauthorizedUser() {
ResponseEntity<Object> entity = userRestTemplate().getForEntity("/actuator/env", Object.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN);
}
@Test
void actuatorSecureEndpointWithAuthorizedUser() {
ResponseEntity<Object> entity = adminRestTemplate().getForEntity("/actuator/env", Object.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
}
@Test
void actuatorCustomMvcSecureEndpointWithAnonymous() {
ResponseEntity<String> entity = restTemplate().getForEntity("/actuator/example/echo?text={t}", String.class,
"test");
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
}
@Test
void actuatorCustomMvcSecureEndpointWithUnauthorizedUser() {
ResponseEntity<String> entity = userRestTemplate().getForEntity("/actuator/example/echo?text={t}", String.class,
"test");
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN);
}
@Test
void actuatorCustomMvcSecureEndpointWithAuthorizedUser() {
ResponseEntity<String> entity = adminRestTemplate().getForEntity("/actuator/example/echo?text={t}",
String.class, "test");
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(entity.getBody()).isEqualTo("test");
assertThat(entity.getHeaders().getFirst("echo")).isEqualTo("test");
}
@Test
void actuatorExcludedFromEndpointRequestMatcher() {
ResponseEntity<Object> entity = userRestTemplate().getForEntity("/actuator/mappings", Object.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
}
@Test
void mvcMatchersCanBeUsedToSecureActuators() {
ResponseEntity<Object> entity = beansRestTemplate().getForEntity("/actuator/beans", Object.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
entity = beansRestTemplate().getForEntity("/actuator/beans/", Object.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
}
private TestRestTemplate restTemplate() {
return configure(new TestRestTemplate());
}
private TestRestTemplate adminRestTemplate() {
return configure(new TestRestTemplate("admin", "admin"));
}
private TestRestTemplate userRestTemplate() {
return configure(new TestRestTemplate("user", "password"));
}
private TestRestTemplate beansRestTemplate() {
return configure(new TestRestTemplate("beans", "beans"));
}
private TestRestTemplate configure(TestRestTemplate restTemplate) {
restTemplate.setUriTemplateHandler(new LocalHostUriTemplateHandler(this.environment));
return restTemplate;
}
}

@ -1,60 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<!-- Your own application should inherit from spring-boot-starter-parent -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-samples</artifactId>
<version>${revision}</version>
</parent>
<artifactId>spring-boot-sample-actuator-log4j2</artifactId>
<name>Spring Boot Actuator Log4j 2 Sample</name>
<description>Spring Boot Actuator Log4j 2 Sample</description>
<properties>
<main.basedir>${basedir}/../..</main.basedir>
</properties>
<dependencies>
<!-- Compile -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- Test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

@ -1,29 +0,0 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.actuator.log4j2;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SampleActuatorLog4J2Application {
public static void main(String[] args) {
SpringApplication.run(SampleActuatorLog4J2Application.class, args);
}
}

@ -1,72 +0,0 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.actuator.log4j2;
import java.util.Base64;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.system.CapturedOutput;
import org.springframework.boot.test.system.OutputCaptureExtension;
import org.springframework.test.web.servlet.MockMvc;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
/**
* Tests for {@link SampleActuatorLog4J2Application}.
*
* @author Dave Syer
* @author Stephane Nicoll
*/
@SpringBootTest
@AutoConfigureMockMvc
@ExtendWith(OutputCaptureExtension.class)
class SampleActuatorLog4J2ApplicationTests {
private static final Logger logger = LogManager.getLogger(SampleActuatorLog4J2ApplicationTests.class);
@Autowired
private MockMvc mvc;
@Test
void testLogger(CapturedOutput capturedOutput) {
logger.info("Hello World");
assertThat(capturedOutput).contains("Hello World");
}
@Test
void validateLoggersEndpoint() throws Exception {
this.mvc.perform(get("/actuator/loggers/org.apache.coyote.http11.Http11NioProtocol").header("Authorization",
"Basic " + getBasicAuth())).andExpect(status().isOk()).andExpect(
content().string(equalTo("{\"configuredLevel\":\"WARN\"," + "\"effectiveLevel\":\"WARN\"}")));
}
private String getBasicAuth() {
return new String(Base64.getEncoder().encode(("user:password").getBytes()));
}
}

@ -1,44 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<!-- Your own application should inherit from spring-boot-starter-parent -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-samples</artifactId>
<version>${revision}</version>
</parent>
<artifactId>spring-boot-sample-actuator-noweb</artifactId>
<name>Spring Boot Actuator Non-Web Sample</name>
<description>Spring Boot Actuator Non-Web Sample</description>
<properties>
<main.basedir>${basedir}/../..</main.basedir>
</properties>
<dependencies>
<!-- Compile -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!-- Optional -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<!-- Test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

@ -1,34 +0,0 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.actuator.noweb;
import org.springframework.stereotype.Component;
@Component
public class HelloWorldService {
private final ServiceProperties configuration;
public HelloWorldService(ServiceProperties configuration) {
this.configuration = configuration;
}
public String getHelloMessage() {
return "Hello " + this.configuration.getName();
}
}

@ -1,29 +0,0 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.actuator.noweb;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SampleActuatorNoWebApplication {
public static void main(String[] args) {
SpringApplication.run(SampleActuatorNoWebApplication.class, args);
}
}

@ -1,37 +0,0 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.actuator.noweb;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties(prefix = "service", ignoreUnknownFields = false)
public class ServiceProperties {
/**
* Name of the service.
*/
private String name = "World";
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
}

@ -1,36 +0,0 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.actuator.noweb;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
/**
* Basic integration tests for service demo application.
*
* @author Dave Syer
*/
@SpringBootTest
class SampleActuatorNoWebApplicationTests {
@Test
void contextLoads() {
}
}

@ -1,54 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<!-- Your own application should inherit from spring-boot-starter-parent -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-samples</artifactId>
<version>${revision}</version>
</parent>
<artifactId>spring-boot-sample-actuator-ui</artifactId>
<name>Spring Boot Actuator UI Sample</name>
<description>Spring Boot Actuator UI Sample</description>
<properties>
<main.basedir>${basedir}/../..</main.basedir>
</properties>
<dependencies>
<!-- Compile -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.jolokia</groupId>
<artifactId>jolokia-core</artifactId>
</dependency>
<!-- Test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

@ -1,49 +0,0 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.actuator.ui;
import java.util.Date;
import java.util.Map;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
@SpringBootApplication
@Controller
public class SampleActuatorUiApplication {
@GetMapping("/")
public String home(Map<String, Object> model) {
model.put("message", "Hello World");
model.put("title", "Hello Home");
model.put("date", new Date());
return "home";
}
@RequestMapping("/foo")
public String foo() {
throw new RuntimeException("Expected exception in controller");
}
public static void main(String[] args) {
SpringApplication.run(SampleActuatorUiApplication.class, args);
}
}

@ -1,74 +0,0 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.actuator.ui;
import java.util.Map;
import org.junit.jupiter.api.Test;
import org.springframework.boot.actuate.autoconfigure.web.server.LocalManagementPort;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Integration tests for separate management and main service ports.
*
* @author Dave Syer
*/
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = { "management.server.port:0" })
class SampleActuatorUiApplicationPortTests {
@LocalServerPort
private int port;
@LocalManagementPort
private int managementPort;
@Test
void testHome() {
ResponseEntity<String> entity = new TestRestTemplate().getForEntity("http://localhost:" + this.port,
String.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
}
@Test
void testMetrics() {
@SuppressWarnings("rawtypes")
ResponseEntity<Map> entity = new TestRestTemplate()
.getForEntity("http://localhost:" + this.managementPort + "/actuator/metrics", Map.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
}
@Test
void testHealth() {
ResponseEntity<String> entity = new TestRestTemplate().withBasicAuth("user", getPassword())
.getForEntity("http://localhost:" + this.managementPort + "/actuator/health", String.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(entity.getBody()).contains("\"status\":\"UP\"");
}
private String getPassword() {
return "password";
}
}

@ -1,87 +0,0 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.actuator.ui;
import java.util.Arrays;
import java.util.Map;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Basic integration tests for demo application.
*
* @author Dave Syer
*/
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
class SampleActuatorUiApplicationTests {
@Autowired
private TestRestTemplate restTemplate;
@Test
void testHome() {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.TEXT_HTML));
ResponseEntity<String> entity = this.restTemplate.withBasicAuth("user", getPassword()).exchange("/",
HttpMethod.GET, new HttpEntity<Void>(headers), String.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(entity.getBody()).contains("<title>Hello");
}
@Test
void testCss() {
ResponseEntity<String> entity = this.restTemplate.getForEntity("/css/bootstrap.min.css", String.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(entity.getBody()).contains("body");
}
@Test
void testMetrics() {
@SuppressWarnings("rawtypes")
ResponseEntity<Map> entity = this.restTemplate.getForEntity("/actuator/metrics", Map.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
}
@Test
void testError() {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.TEXT_HTML));
ResponseEntity<String> entity = this.restTemplate.withBasicAuth("user", getPassword()).exchange("/error",
HttpMethod.GET, new HttpEntity<Void>(headers), String.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR);
assertThat(entity.getBody()).contains("<html>").contains("<body>")
.contains("Please contact the operator with the above information");
}
private String getPassword() {
return "password";
}
}

@ -1,86 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<!-- Your own application should inherit from spring-boot-starter-parent -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-samples</artifactId>
<version>${revision}</version>
</parent>
<artifactId>spring-boot-sample-actuator</artifactId>
<name>Spring Boot Actuator Sample</name>
<description>Spring Boot Actuator Sample</description>
<properties>
<main.basedir>${basedir}/../..</main.basedir>
</properties>
<dependencies>
<!-- Compile -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!-- Runtime -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<!-- Optional -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<!-- Test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<executable>true</executable>
</configuration>
<executions>
<execution>
<id>generate build info</id>
<goals>
<goal>build-info</goal>
</goals>
<configuration>
<additionalProperties>
<encoding.source>${project.build.sourceEncoding}</encoding.source>
<encoding.reporting>${project.reporting.outputEncoding}</encoding.reporting>
<java.source>${maven.compiler.source}</java.source>
<java.target>${maven.compiler.target}</java.target>
</additionalProperties>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

@ -1,31 +0,0 @@
/*
* Copyright 2012-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.actuator;
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.stereotype.Component;
@Component
public class ExampleHealthIndicator implements HealthIndicator {
@Override
public Health health() {
return Health.up().withDetail("counter", 42).build();
}
}

@ -1,33 +0,0 @@
/*
* Copyright 2012-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.actuator;
import java.util.Collections;
import org.springframework.boot.actuate.info.Info;
import org.springframework.boot.actuate.info.InfoContributor;
import org.springframework.stereotype.Component;
@Component
public class ExampleInfoContributor implements InfoContributor {
@Override
public void contribute(Info.Builder builder) {
builder.withDetail("example", Collections.singletonMap("someKey", "someValue"));
}
}

@ -1,34 +0,0 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.actuator;
import org.springframework.stereotype.Component;
@Component
public class HelloWorldService {
private final ServiceProperties configuration;
public HelloWorldService(ServiceProperties configuration) {
this.configuration = configuration;
}
public String getHelloMessage() {
return "Hello " + this.configuration.getName();
}
}

@ -1,37 +0,0 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.actuator;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class SampleActuatorApplication {
public static void main(String[] args) {
SpringApplication.run(SampleActuatorApplication.class, args);
}
@Bean
public HealthIndicator helloHealthIndicator() {
return () -> Health.up().withDetail("hello", "world").build();
}
}

@ -1,82 +0,0 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.actuator;
import java.util.Collections;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.validation.constraints.NotBlank;
import org.springframework.context.annotation.Description;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@Description("A controller for handling requests for hello messages")
public class SampleController {
private final HelloWorldService helloWorldService;
public SampleController(HelloWorldService helloWorldService) {
this.helloWorldService = helloWorldService;
}
@GetMapping(value = "/", produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public Map<String, String> hello() {
return Collections.singletonMap("message", this.helloWorldService.getHelloMessage());
}
@PostMapping(value = "/", produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public Map<String, Object> olleh(@Validated Message message) {
Map<String, Object> model = new LinkedHashMap<>();
model.put("message", message.getValue());
model.put("title", "Hello Home");
model.put("date", new Date());
return model;
}
@RequestMapping("/foo")
@ResponseBody
public String foo() {
throw new IllegalArgumentException("Server error");
}
protected static class Message {
@NotBlank(message = "Message value cannot be empty")
private String value;
public String getValue() {
return this.value;
}
public void setValue(String value) {
this.value = value;
}
}
}

@ -1,37 +0,0 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.actuator;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties(prefix = "service", ignoreUnknownFields = false)
public class ServiceProperties {
/**
* Name of the service.
*/
private String name = "World";
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
}

@ -1,70 +0,0 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.actuator;
import java.util.Map;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.ActiveProfiles;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Integration tests for endpoints configuration.
*
* @author Dave Syer
*/
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
@ActiveProfiles("endpoints")
class EndpointsPropertiesSampleActuatorApplicationTests {
@Autowired
private TestRestTemplate restTemplate;
@Test
void testCustomErrorPath() {
@SuppressWarnings("rawtypes")
ResponseEntity<Map> entity = this.restTemplate.withBasicAuth("user", getPassword()).getForEntity("/oops",
Map.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR);
@SuppressWarnings("unchecked")
Map<String, Object> body = entity.getBody();
assertThat(body.get("error")).isEqualTo("None");
assertThat(body.get("status")).isEqualTo(999);
}
@Test
void testCustomContextPath() {
ResponseEntity<String> entity = this.restTemplate.withBasicAuth("user", getPassword())
.getForEntity("/admin/health", String.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(entity.getBody()).contains("\"status\":\"UP\"");
assertThat(entity.getBody()).contains("\"hello\":\"world\"");
}
private String getPassword() {
return "password";
}
}

@ -1,67 +0,0 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.actuator;
import java.util.Map;
import org.junit.jupiter.api.Test;
import org.springframework.boot.actuate.autoconfigure.web.server.LocalManagementPort;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Integration tests for separate management and main service ports.
*
* @author Dave Syer
*/
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = { "management.server.port=0",
"management.server.address=127.0.0.1", "management.server.servlet.context-path:/admin" })
class ManagementAddressActuatorApplicationTests {
@LocalServerPort
private int port;
@LocalManagementPort
private int managementPort;
@Test
void testHome() {
@SuppressWarnings("rawtypes")
ResponseEntity<Map> entity = new TestRestTemplate().getForEntity("http://localhost:" + this.port, Map.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
}
@Test
void testHealth() {
ResponseEntity<String> entity = new TestRestTemplate().withBasicAuth("user", getPassword())
.getForEntity("http://localhost:" + this.managementPort + "/admin/actuator/health", String.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(entity.getBody()).contains("\"status\":\"UP\"");
}
private String getPassword() {
return "password";
}
}

@ -1,67 +0,0 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.actuator;
import java.util.Map;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Integration tests for endpoints configuration.
*
* @author Dave Syer
*/
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT,
properties = { "management.endpoints.web.base-path=/admin" })
class ManagementPathSampleActuatorApplicationTests {
@Autowired
private TestRestTemplate restTemplate;
@Test
void testHealth() {
ResponseEntity<String> entity = this.restTemplate.withBasicAuth("user", getPassword())
.getForEntity("/admin/health", String.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(entity.getBody()).contains("\"status\":\"UP\"");
}
@Test
void testHomeIsSecure() {
@SuppressWarnings("rawtypes")
ResponseEntity<Map> entity = this.restTemplate.getForEntity("/", Map.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
@SuppressWarnings("unchecked")
Map<String, Object> body = entity.getBody();
assertThat(body.get("error")).isEqualTo("Unauthorized");
assertThat(entity.getHeaders()).doesNotContainKey("Set-Cookie");
}
private String getPassword() {
return "password";
}
}

@ -1,124 +0,0 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.actuator;
import java.util.Map;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.autoconfigure.web.server.LocalManagementPort;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.core.env.Environment;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Integration tests for separate management and main service ports.
*
* @author Dave Syer
*/
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = { "management.server.port=0",
"management.endpoints.web.base-path=/admin", "management.endpoint.health.show-details=never" })
class ManagementPortAndPathSampleActuatorApplicationTests {
@LocalServerPort
private int port;
@LocalManagementPort
private int managementPort;
@Autowired
private Environment environment;
@Test
void testHome() {
@SuppressWarnings("rawtypes")
ResponseEntity<Map> entity = new TestRestTemplate("user", getPassword())
.getForEntity("http://localhost:" + this.port, Map.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
@SuppressWarnings("unchecked")
Map<String, Object> body = entity.getBody();
assertThat(body.get("message")).isEqualTo("Hello Phil");
}
@Test
void testMetrics() {
testHome(); // makes sure some requests have been made
@SuppressWarnings("rawtypes")
ResponseEntity<Map> entity = new TestRestTemplate()
.getForEntity("http://localhost:" + this.managementPort + "/admin/metrics", Map.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
}
@Test
void testHealth() {
ResponseEntity<String> entity = new TestRestTemplate().withBasicAuth("user", getPassword())
.getForEntity("http://localhost:" + this.managementPort + "/admin/health", String.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(entity.getBody()).isEqualTo("{\"status\":\"UP\"}");
}
@Test
void testEnvNotFound() {
String unknownProperty = "test-does-not-exist";
assertThat(this.environment.containsProperty(unknownProperty)).isFalse();
ResponseEntity<String> entity = new TestRestTemplate().withBasicAuth("user", getPassword()).getForEntity(
"http://localhost:" + this.managementPort + "/admin/env/" + unknownProperty, String.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND);
}
@Test
void testMissing() {
ResponseEntity<String> entity = new TestRestTemplate("user", getPassword())
.getForEntity("http://localhost:" + this.managementPort + "/admin/missing", String.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND);
assertThat(entity.getBody()).contains("\"status\":404");
}
@Test
void testErrorPage() {
@SuppressWarnings("rawtypes")
ResponseEntity<Map> entity = new TestRestTemplate("user", getPassword())
.getForEntity("http://localhost:" + this.port + "/error", Map.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR);
@SuppressWarnings("unchecked")
Map<String, Object> body = entity.getBody();
assertThat(body.get("status")).isEqualTo(999);
}
@Test
void testManagementErrorPage() {
@SuppressWarnings("rawtypes")
ResponseEntity<Map> entity = new TestRestTemplate("user", getPassword())
.getForEntity("http://localhost:" + this.managementPort + "/error", Map.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
@SuppressWarnings("unchecked")
Map<String, Object> body = entity.getBody();
assertThat(body.get("status")).isEqualTo(999);
}
private String getPassword() {
return "password";
}
}

@ -1,93 +0,0 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.actuator;
import java.util.Map;
import org.junit.jupiter.api.Test;
import org.springframework.boot.actuate.autoconfigure.web.server.LocalManagementPort;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Integration tests for separate management and main service ports.
*
* @author Dave Syer
*/
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT,
properties = { "management.server.port=0", "management.endpoint.health.show-details=always" })
class ManagementPortSampleActuatorApplicationTests {
@LocalServerPort
private int port;
@LocalManagementPort
private int managementPort;
@Test
void testHome() {
@SuppressWarnings("rawtypes")
ResponseEntity<Map> entity = new TestRestTemplate("user", getPassword())
.getForEntity("http://localhost:" + this.port, Map.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
@SuppressWarnings("unchecked")
Map<String, Object> body = entity.getBody();
assertThat(body.get("message")).isEqualTo("Hello Phil");
}
@Test
void testMetrics() {
testHome(); // makes sure some requests have been made
@SuppressWarnings("rawtypes")
ResponseEntity<Map> entity = new TestRestTemplate()
.getForEntity("http://localhost:" + this.managementPort + "/actuator/metrics", Map.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
}
@Test
void testHealth() {
ResponseEntity<String> entity = new TestRestTemplate().withBasicAuth("user", getPassword())
.getForEntity("http://localhost:" + this.managementPort + "/actuator/health", String.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(entity.getBody()).contains("\"status\":\"UP\"");
assertThat(entity.getBody()).contains("\"example\"");
assertThat(entity.getBody()).contains("\"counter\":42");
}
@Test
void testErrorPage() {
@SuppressWarnings("rawtypes")
ResponseEntity<Map> entity = new TestRestTemplate("user", getPassword())
.getForEntity("http://localhost:" + this.managementPort + "/error", Map.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
@SuppressWarnings("unchecked")
Map<String, Object> body = entity.getBody();
assertThat(body.get("status")).isEqualTo(999);
}
private String getPassword() {
return "password";
}
}

@ -1,50 +0,0 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.actuator;
import org.junit.jupiter.api.Test;
import org.springframework.boot.actuate.autoconfigure.web.server.LocalManagementPort;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Integration tests for separate management and main service ports when
* lazy-initialization is enabled.
*
* @author Madhura Bhave
*/
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
properties = { "management.server.port=0", "spring.main.lazy-initialization=true" })
class ManagementPortWithLazyInitializationTests {
@LocalManagementPort
private int managementPort;
@Test
void testHealth() {
ResponseEntity<String> entity = new TestRestTemplate().withBasicAuth("user", "password")
.getForEntity("http://localhost:" + this.managementPort + "/actuator/health", String.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(entity.getBody()).contains("\"status\":\"UP\"");
}
}

@ -1,67 +0,0 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.actuator;
import java.util.Map;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Integration tests for switching off management endpoints.
*
* @author Dave Syer
*/
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = { "management.server.port=-1" })
class NoManagementSampleActuatorApplicationTests {
@Autowired
private TestRestTemplate restTemplate;
@Test
void testHome() {
@SuppressWarnings("rawtypes")
ResponseEntity<Map> entity = this.restTemplate.withBasicAuth("user", getPassword()).getForEntity("/",
Map.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
@SuppressWarnings("unchecked")
Map<String, Object> body = entity.getBody();
assertThat(body.get("message")).isEqualTo("Hello Phil");
}
@Test
void testMetricsNotAvailable() {
testHome(); // makes sure some requests have been made
@SuppressWarnings("rawtypes")
ResponseEntity<Map> entity = this.restTemplate.withBasicAuth("user", getPassword()).getForEntity("/metrics",
Map.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND);
}
private String getPassword() {
return "password";
}
}

@ -1,195 +0,0 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.actuator;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.context.ApplicationContext;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Basic integration tests for service demo application.
*
* @author Dave Syer
* @author Stephane Nicoll
*/
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
class SampleActuatorApplicationTests {
@Autowired
private TestRestTemplate restTemplate;
@Autowired
private ApplicationContext applicationContext;
@Test
void testHomeIsSecure() {
@SuppressWarnings("rawtypes")
ResponseEntity<Map> entity = this.restTemplate.getForEntity("/", Map.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
@SuppressWarnings("unchecked")
Map<String, Object> body = entity.getBody();
assertThat(body.get("error")).isEqualTo("Unauthorized");
assertThat(entity.getHeaders()).doesNotContainKey("Set-Cookie");
}
@Test
void testMetricsIsSecure() {
@SuppressWarnings("rawtypes")
ResponseEntity<Map> entity = this.restTemplate.getForEntity("/actuator/metrics", Map.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
entity = this.restTemplate.getForEntity("/actuator/metrics/", Map.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
entity = this.restTemplate.getForEntity("/actuator/metrics/foo", Map.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
entity = this.restTemplate.getForEntity("/actuator/metrics.json", Map.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
}
@Test
void testHome() {
@SuppressWarnings("rawtypes")
ResponseEntity<Map> entity = this.restTemplate.withBasicAuth("user", getPassword()).getForEntity("/",
Map.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
@SuppressWarnings("unchecked")
Map<String, Object> body = entity.getBody();
assertThat(body.get("message")).isEqualTo("Hello Phil");
}
@SuppressWarnings("unchecked")
@Test
void testMetrics() {
testHome(); // makes sure some requests have been made
@SuppressWarnings("rawtypes")
ResponseEntity<Map> entity = this.restTemplate.withBasicAuth("user", getPassword())
.getForEntity("/actuator/metrics", Map.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
Map<String, Object> body = entity.getBody();
assertThat(body).containsKey("names");
assertThat((List<String>) body.get("names")).contains("jvm.buffer.count");
}
@Test
void testEnv() {
@SuppressWarnings("rawtypes")
ResponseEntity<Map> entity = this.restTemplate.withBasicAuth("user", getPassword())
.getForEntity("/actuator/env", Map.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
@SuppressWarnings("unchecked")
Map<String, Object> body = entity.getBody();
assertThat(body).containsKey("propertySources");
}
@Test
void healthInsecureByDefault() {
ResponseEntity<String> entity = this.restTemplate.getForEntity("/actuator/health", String.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(entity.getBody()).contains("\"status\":\"UP\"");
assertThat(entity.getBody()).doesNotContain("\"hello\":\"1\"");
}
@Test
void infoInsecureByDefault() {
ResponseEntity<String> entity = this.restTemplate.getForEntity("/actuator/info", String.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(entity.getBody()).contains("\"artifact\":\"spring-boot-sample-actuator\"");
assertThat(entity.getBody()).contains("\"someKey\":\"someValue\"");
assertThat(entity.getBody()).contains("\"java\":{", "\"source\":\"1.8\"", "\"target\":\"1.8\"");
assertThat(entity.getBody()).contains("\"encoding\":{", "\"source\":\"UTF-8\"", "\"reporting\":\"UTF-8\"");
}
@Test
void testErrorPage() {
ResponseEntity<String> entity = this.restTemplate.withBasicAuth("user", getPassword()).getForEntity("/foo",
String.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR);
String body = entity.getBody();
assertThat(body).contains("\"error\":");
}
@Test
void testHtmlErrorPage() {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.TEXT_HTML));
HttpEntity<?> request = new HttpEntity<Void>(headers);
ResponseEntity<String> entity = this.restTemplate.withBasicAuth("user", getPassword()).exchange("/foo",
HttpMethod.GET, request, String.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR);
String body = entity.getBody();
assertThat(body).as("Body was null").isNotNull();
assertThat(body).contains("This application has no explicit mapping for /error");
}
@Test
void testErrorPageDirectAccess() {
@SuppressWarnings("rawtypes")
ResponseEntity<Map> entity = this.restTemplate.withBasicAuth("user", getPassword()).getForEntity("/error",
Map.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR);
@SuppressWarnings("unchecked")
Map<String, Object> body = entity.getBody();
assertThat(body.get("error")).isEqualTo("None");
assertThat(body.get("status")).isEqualTo(999);
}
@Test
@SuppressWarnings("unchecked")
void testBeans() {
@SuppressWarnings("rawtypes")
ResponseEntity<Map> entity = this.restTemplate.withBasicAuth("user", getPassword())
.getForEntity("/actuator/beans", Map.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(entity.getBody()).containsOnlyKeys("contexts");
}
@SuppressWarnings("unchecked")
@Test
void testConfigProps() {
@SuppressWarnings("rawtypes")
ResponseEntity<Map> entity = this.restTemplate.withBasicAuth("user", getPassword())
.getForEntity("/actuator/configprops", Map.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
Map<String, Object> body = entity.getBody();
Map<String, Object> contexts = (Map<String, Object>) body.get("contexts");
Map<String, Object> context = (Map<String, Object>) contexts.get(this.applicationContext.getId());
Map<String, Object> beans = (Map<String, Object>) context.get("beans");
assertThat(beans).containsKey("spring.datasource-" + DataSourceProperties.class.getName());
}
private String getPassword() {
return "password";
}
}

@ -1,78 +0,0 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.actuator;
import java.util.Map;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Integration tests for endpoints configuration.
*
* @author Dave Syer
*/
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = { "spring.mvc.servlet.path=/spring" })
class ServletPathSampleActuatorApplicationTests {
@Autowired
private TestRestTemplate restTemplate;
@Test
void testErrorPath() {
@SuppressWarnings("rawtypes")
ResponseEntity<Map> entity = this.restTemplate.withBasicAuth("user", getPassword())
.getForEntity("/spring/error", Map.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR);
@SuppressWarnings("unchecked")
Map<String, Object> body = entity.getBody();
assertThat(body.get("error")).isEqualTo("None");
assertThat(body.get("status")).isEqualTo(999);
}
@Test
void testHealth() {
ResponseEntity<String> entity = this.restTemplate.withBasicAuth("user", getPassword())
.getForEntity("/spring/actuator/health", String.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(entity.getBody()).contains("\"status\":\"UP\"");
}
@Test
void testHomeIsSecure() {
@SuppressWarnings("rawtypes")
ResponseEntity<Map> entity = this.restTemplate.getForEntity("/spring/", Map.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
@SuppressWarnings("unchecked")
Map<String, Object> body = entity.getBody();
assertThat(body.get("error")).isEqualTo("Unauthorized");
assertThat(entity.getHeaders()).doesNotContainKey("Set-Cookie");
}
private String getPassword() {
return "password";
}
}

@ -1,85 +0,0 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.actuator;
import java.util.Map;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.test.annotation.DirtiesContext;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Integration tests for separate management and main service ports.
*
* @author Dave Syer
*/
@SpringBootTest(classes = { ShutdownSampleActuatorApplicationTests.SecurityConfiguration.class,
SampleActuatorApplication.class }, webEnvironment = WebEnvironment.RANDOM_PORT)
class ShutdownSampleActuatorApplicationTests {
@Autowired
private TestRestTemplate restTemplate;
@Test
void testHome() {
@SuppressWarnings("rawtypes")
ResponseEntity<Map> entity = this.restTemplate.withBasicAuth("user", getPassword()).getForEntity("/",
Map.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
@SuppressWarnings("unchecked")
Map<String, Object> body = entity.getBody();
assertThat(body.get("message")).isEqualTo("Hello Phil");
}
@Test
@DirtiesContext
void testShutdown() {
@SuppressWarnings("rawtypes")
ResponseEntity<Map> entity = this.restTemplate.withBasicAuth("user", getPassword())
.postForEntity("/actuator/shutdown", null, Map.class);
assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
@SuppressWarnings("unchecked")
Map<String, Object> body = entity.getBody();
assertThat(((String) body.get("message"))).contains("Shutting down");
}
private String getPassword() {
return "password";
}
@Configuration(proxyBeanMethods = false)
static class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
}
}
}

@ -1,39 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<!-- Your own application should inherit from spring-boot-starter-parent -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-samples</artifactId>
<version>${revision}</version>
</parent>
<artifactId>spring-boot-sample-amqp</artifactId>
<name>Spring Boot AMQP Sample</name>
<description>Spring Boot AMQP Sample</description>
<properties>
<main.basedir>${basedir}/../..</main.basedir>
</properties>
<dependencies>
<!-- Compile -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
<!-- Test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

@ -1,54 +0,0 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.amqp;
import java.util.Date;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@RabbitListener(queues = "foo")
@EnableScheduling
public class SampleAmqpSimpleApplication {
@Bean
public Sender mySender() {
return new Sender();
}
@Bean
public Queue fooQueue() {
return new Queue("foo");
}
@RabbitHandler
public void process(@Payload String foo) {
System.out.println(new Date() + ": " + foo);
}
public static void main(String[] args) {
SpringApplication.run(SampleAmqpSimpleApplication.class, args);
}
}

@ -1,33 +0,0 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.amqp;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
public class Sender {
@Autowired
private RabbitTemplate rabbitTemplate;
@Scheduled(fixedDelay = 1000L)
public void send() {
this.rabbitTemplate.convertAndSend("foo", "hello");
}
}

@ -1,38 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<!-- Your own application should inherit from spring-boot-starter-parent -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-samples</artifactId>
<version>${revision}</version>
</parent>
<artifactId>spring-boot-sample-animated-banner</artifactId>
<name>Spring Boot Simple Animated Banner</name>
<description>Spring Boot Simple Animated Banner</description>
<properties>
<main.basedir>${basedir}/../..</main.basedir>
</properties>
<dependencies>
<!-- Compile -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<!-- Test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

@ -1,29 +0,0 @@
/*
* Copyright 2012-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.animated;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SampleAnimatedBannerApplication {
public static void main(String[] args) {
SpringApplication.run(SampleAnimatedBannerApplication.class, args);
}
}

@ -1,69 +0,0 @@
<project
xmlns:ivy="antlib:org.apache.ivy.ant"
xmlns:spring-boot="antlib:org.springframework.boot.ant"
name="spring-boot-sample-ant"
default="build">
<description>
Sample ANT build script for a Spring Boot executable JAR project. Uses ivy for
dependency management and spring-boot-antlib for additional tasks. Run with
'$ ant -lib ivy-2.2.jar spring-boot-antlib.jar' (substitute the location of your
actual jars). Run with '$ java -jar target/*.jar'.
</description>
<property name="ant-spring-boot.version" value="${revision}" />
<property name="lib.dir" location="${basedir}/target/lib" />
<property name="start-class" value="sample.ant.SampleAntApplication" />
<target name="resolve" description="--> retrieve dependencies with ivy">
<ivy:retrieve pattern="${lib.dir}/[conf]/[artifact]-[type]-[revision].[ext]" />
</target>
<target name="classpaths" depends="resolve">
<path id="compile.classpath">
<fileset dir="${lib.dir}/compile" includes="*.jar" />
</path>
</target>
<target name="init" depends="classpaths">
<mkdir dir="target/classes" />
</target>
<target name="compile" depends="init" description="compile">
<javac srcdir="src/main/java" destdir="target/classes" classpathref="compile.classpath" />
</target>
<target name="clean" description="cleans all created files/dirs">
<delete dir="target" />
</target>
<target name="build" depends="compile">
<spring-boot:exejar destfile="target/${ant.project.name}-${ant-spring-boot.version}.jar" classes="target/classes">
<spring-boot:lib>
<fileset dir="${lib.dir}/runtime" />
</spring-boot:lib>
</spring-boot:exejar>
</target>
<!-- Manual equivalent of the build target -->
<target name="manual" depends="compile">
<jar destfile="target/${ant.project.name}-${ant-spring-boot.version}.jar" compress="false">
<mappedresources>
<fileset dir="target/classes" />
<globmapper from="*" to="BOOT-INF/classes/*"/>
</mappedresources>
<mappedresources>
<fileset dir="src/main/resources" erroronmissingdir="false"/>
<globmapper from="*" to="BOOT-INF/classes/*"/>
</mappedresources>
<mappedresources>
<fileset dir="${lib.dir}/runtime" />
<globmapper from="*" to="BOOT-INF/lib/*"/>
</mappedresources>
<zipfileset src="${lib.dir}/loader/spring-boot-loader-jar-${ant-spring-boot.version}.jar" />
<manifest>
<attribute name="Main-Class" value="org.springframework.boot.loader.JarLauncher" />
<attribute name="Start-Class" value="${start-class}" />
</manifest>
</jar>
</target>
</project>

@ -1,12 +0,0 @@
<ivy-module version="2.0">
<info organisation="org.springframework.boot" module="spring-boot-sample-ant" />
<configurations>
<conf name="compile" description="everything needed to compile this module" />
<conf name="runtime" extends="compile" description="everything needed to run this module" />
<conf name="loader" description="Spring Boot loader used when manually building an executable archive" />
</configurations>
<dependencies>
<dependency org="org.springframework.boot" name="spring-boot-starter" rev="${ant-spring-boot.version}" conf="compile" />
<dependency org="org.springframework.boot" name="spring-boot-loader" rev="${ant-spring-boot.version}" conf="loader->default" />
</dependencies>
</ivy-module>

@ -1,107 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<!-- This POM is just to trigger the Ant/Ivy sample from Maven and to test -->
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-samples</artifactId>
<version>${revision}</version>
</parent>
<artifactId>spring-boot-sample-ant</artifactId>
<name>Spring Boot Ant Sample</name>
<description>Spring Boot Ant Sample</description>
<properties>
<main.basedir>${basedir}/../..</main.basedir>
<ant.version>1.9.3</ant.version>
</properties>
<dependencies>
<!-- Compile -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-loader</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-antlib</artifactId>
<version>${project.version}</version>
</dependency>
<!-- Test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-loader-tools</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<executions>
<execution>
<id>default-compile</id>
<phase>none</phase>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-antrun-plugin</artifactId>
<executions>
<execution>
<id>antbuild</id>
<phase>package</phase>
<configuration>
<target>
<property name="build.compiler" value="extJavac" />
<ant dir="${basedir}" />
</target>
</configuration>
<goals>
<goal>run</goal>
</goals>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>org.apache.ant</groupId>
<artifactId>ant</artifactId>
<version>${ant.version}</version>
</dependency>
<dependency>
<groupId>org.apache.ivy</groupId>
<artifactId>ivy</artifactId>
<version>2.4.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-antlib</artifactId>
<version>${revision}</version>
</dependency>
</dependencies>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-failsafe-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>integration-test</goal>
<goal>verify</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

@ -1,35 +0,0 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.ant;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SampleAntApplication implements CommandLineRunner {
@Override
public void run(String... args) {
System.out.println("Spring Boot Ant Example");
}
public static void main(String[] args) {
SpringApplication.run(SampleAntApplication.class, args);
}
}

@ -1,58 +0,0 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.ant;
import java.io.File;
import java.io.FileFilter;
import java.io.InputStreamReader;
import java.util.concurrent.TimeUnit;
import org.junit.jupiter.api.Test;
import org.springframework.boot.loader.tools.JavaExecutable;
import org.springframework.util.FileCopyUtils;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Integration Tests for {@code SampleAntApplication}.
*
* @author Dave Syer
* @author Phillip Webb
*/
public class SampleAntApplicationIT {
@Test
void runJar() throws Exception {
File target = new File("target");
File[] jarFiles = target.listFiles(new FileFilter() {
@Override
public boolean accept(File file) {
return file.getName().endsWith(".jar");
}
});
assertThat(jarFiles).hasSize(1);
Process process = new JavaExecutable().processBuilder("-jar", jarFiles[0].getName()).directory(target).start();
process.waitFor(5, TimeUnit.MINUTES);
assertThat(process.exitValue()).isEqualTo(0);
String output = FileCopyUtils.copyToString(new InputStreamReader(process.getInputStream()));
assertThat(output).contains("Spring Boot Ant Example");
}
}

@ -1,38 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<!-- Your own application should inherit from spring-boot-starter-parent -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-samples</artifactId>
<version>${revision}</version>
</parent>
<artifactId>spring-boot-sample-aop</artifactId>
<name>Spring Boot AOP Sample</name>
<description>Spring Boot AOP Sample</description>
<properties>
<main.basedir>${basedir}/../..</main.basedir>
</properties>
<dependencies>
<!-- Compile -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<!-- Test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

@ -1,43 +0,0 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.aop;
import sample.aop.service.HelloWorldService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SampleAopApplication implements CommandLineRunner {
// Simple example shows how an application can spy on itself with AOP
@Autowired
private HelloWorldService helloWorldService;
@Override
public void run(String... args) {
System.out.println(this.helloWorldService.getHelloMessage());
}
public static void main(String[] args) {
SpringApplication.run(SampleAopApplication.class, args);
}
}

@ -1,34 +0,0 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.aop.monitor;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class ServiceMonitor {
@AfterReturning("execution(* sample..*Service.*(..))")
public void logServiceAccess(JoinPoint joinPoint) {
System.out.println("Completed: " + joinPoint);
}
}

@ -1,32 +0,0 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.aop.service;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class HelloWorldService {
@Value("${name:World}")
private String name;
public String getHelloMessage() {
return "Hello " + this.name;
}
}

@ -1,67 +0,0 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.aop;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.boot.test.system.CapturedOutput;
import org.springframework.boot.test.system.OutputCaptureExtension;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link SampleAopApplication}.
*
* @author Dave Syer
* @author Phillip Webb
*/
@ExtendWith(OutputCaptureExtension.class)
class SampleAopApplicationTests {
private String profiles;
@BeforeEach
void init() {
this.profiles = System.getProperty("spring.profiles.active");
}
@AfterEach
void after() {
if (this.profiles != null) {
System.setProperty("spring.profiles.active", this.profiles);
}
else {
System.clearProperty("spring.profiles.active");
}
}
@Test
void testDefaultSettings(CapturedOutput capturedOutput) throws Exception {
SampleAopApplication.main(new String[0]);
assertThat(capturedOutput).contains("Hello Phil");
}
@Test
void testCommandLineOverrides(CapturedOutput capturedOutput) throws Exception {
SampleAopApplication.main(new String[] { "--name=Gordon" });
assertThat(capturedOutput).contains("Hello Gordon");
}
}

@ -1,58 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<!-- Your own application should inherit from spring-boot-starter-parent -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-samples</artifactId>
<version>${revision}</version>
</parent>
<artifactId>spring-boot-sample-atmosphere</artifactId>
<name>Spring Boot Atmosphere Sample</name>
<description>Spring Boot Atmosphere Sample</description>
<properties>
<main.basedir>${basedir}/../..</main.basedir>
</properties>
<dependencies>
<!-- Compile -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>1</version>
</dependency>
<dependency>
<groupId>org.atmosphere</groupId>
<artifactId>atmosphere-runtime</artifactId>
<version>2.4.14</version>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>atmosphere-javascript</artifactId>
<version>2.3.4</version>
</dependency>
<!-- Test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-websocket</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

@ -1,81 +0,0 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.atmosphere;
import java.io.IOException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.atmosphere.config.managed.Decoder;
import org.atmosphere.config.managed.Encoder;
import org.atmosphere.config.service.Disconnect;
import org.atmosphere.config.service.ManagedService;
import org.atmosphere.config.service.Ready;
import org.atmosphere.cpr.AtmosphereResource;
import org.atmosphere.cpr.AtmosphereResourceEvent;
@ManagedService(path = "/chat")
public class ChatService {
private final Log logger = LogFactory.getLog(ChatService.class);
@Ready
public void onReady(AtmosphereResource resource) {
this.logger.info("Connected " + resource.uuid());
}
@Disconnect
public void onDisconnect(AtmosphereResourceEvent event) {
this.logger.info("Client " + event.getResource().uuid() + " disconnected ["
+ (event.isCancelled() ? "cancelled" : "closed") + "]");
}
@org.atmosphere.config.service.Message(encoders = JacksonEncoderDecoder.class,
decoders = JacksonEncoderDecoder.class)
public Message onMessage(Message message) throws IOException {
this.logger.info("Author " + message.getAuthor() + " sent message " + message.getMessage());
return message;
}
public static class JacksonEncoderDecoder implements Encoder<Message, String>, Decoder<String, Message> {
private final ObjectMapper mapper = new ObjectMapper();
@Override
public String encode(Message m) {
try {
return this.mapper.writeValueAsString(m);
}
catch (IOException ex) {
throw new IllegalStateException(ex);
}
}
@Override
public Message decode(String s) {
try {
return this.mapper.readValue(s, Message.class);
}
catch (IOException ex) {
throw new IllegalStateException(ex);
}
}
}
}

@ -1,53 +0,0 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.atmosphere;
import java.util.Date;
public class Message {
private String message;
private String author;
private long time = new Date().getTime();
public String getMessage() {
return this.message;
}
public void setMessage(String message) {
this.message = message;
}
public String getAuthor() {
return this.author;
}
public void setAuthor(String author) {
this.author = author;
}
public long getTime() {
return this.time;
}
public void setTime(long time) {
this.time = time;
}
}

@ -1,88 +0,0 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.atmosphere;
import java.util.Collections;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import org.atmosphere.cpr.AtmosphereServlet;
import org.atmosphere.cpr.ContainerInitializer;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.web.servlet.ServletContextInitializer;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@SpringBootConfiguration
@EnableAutoConfiguration
public class SampleAtmosphereApplication {
@Bean
public EmbeddedAtmosphereInitializer atmosphereInitializer() {
return new EmbeddedAtmosphereInitializer();
}
@Bean
public ServletRegistrationBean<AtmosphereServlet> atmosphereServlet() {
// Dispatcher servlet is mapped to '/home' to allow the AtmosphereServlet
// to be mapped to '/chat'
AtmosphereServlet atmosphereServlet = new AtmosphereServlet();
atmosphereServlet.framework().setHandlersPath("/");
ServletRegistrationBean<AtmosphereServlet> registration = new ServletRegistrationBean<>(atmosphereServlet,
"/chat/*");
registration.addInitParameter("org.atmosphere.cpr.packages", "sample");
registration.addInitParameter(
"org.atmosphere.interceptor.HeartbeatInterceptor" + ".clientHeartbeatFrequencyInSeconds", "10");
registration.setLoadOnStartup(0);
// Need to occur before the EmbeddedAtmosphereInitializer
registration.setOrder(Ordered.HIGHEST_PRECEDENCE);
return registration;
}
public static void main(String[] args) throws Exception {
SpringApplication.run(SampleAtmosphereApplication.class, args);
}
@Configuration(proxyBeanMethods = false)
static class MvcConfiguration implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("forward:/home/home.html");
}
}
private static class EmbeddedAtmosphereInitializer extends ContainerInitializer
implements ServletContextInitializer {
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
onStartup(Collections.emptySet(), servletContext);
}
}
}

@ -1,120 +0,0 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.atmosphere;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.client.WebSocketConnectionManager;
import org.springframework.web.socket.client.standard.StandardWebSocketClient;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import static org.assertj.core.api.Assertions.assertThat;
@SpringBootTest(classes = SampleAtmosphereApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT)
class SampleAtmosphereApplicationTests {
private static Log logger = LogFactory.getLog(SampleAtmosphereApplicationTests.class);
@LocalServerPort
private int port = 1234;
@Test
void chatEndpoint() {
ConfigurableApplicationContext context = new SpringApplicationBuilder(ClientConfiguration.class,
PropertyPlaceholderAutoConfiguration.class)
.properties("websocket.uri:ws://localhost:" + this.port + "/chat/websocket")
.run("--spring.main.web-application-type=none");
long count = context.getBean(ClientConfiguration.class).latch.getCount();
AtomicReference<String> messagePayloadReference = context.getBean(ClientConfiguration.class).messagePayload;
context.close();
assertThat(count).isEqualTo(0L);
assertThat(messagePayloadReference.get()).contains("{\"message\":\"test\",\"author\":\"test\",\"time\":");
}
@Configuration(proxyBeanMethods = false)
static class ClientConfiguration implements CommandLineRunner {
@Value("${websocket.uri}")
private String webSocketUri;
private final CountDownLatch latch = new CountDownLatch(1);
private final AtomicReference<String> messagePayload = new AtomicReference<>();
@Override
public void run(String... args) throws Exception {
logger.info("Waiting for response: latch=" + this.latch.getCount());
if (this.latch.await(10, TimeUnit.SECONDS)) {
logger.info("Got response: " + this.messagePayload.get());
}
else {
logger.info("Response not received: latch=" + this.latch.getCount());
}
}
@Bean
public WebSocketConnectionManager wsConnectionManager() {
WebSocketConnectionManager manager = new WebSocketConnectionManager(client(), handler(), this.webSocketUri);
manager.setAutoStartup(true);
return manager;
}
@Bean
public StandardWebSocketClient client() {
return new StandardWebSocketClient();
}
@Bean
public TextWebSocketHandler handler() {
return new TextWebSocketHandler() {
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
session.sendMessage(new TextMessage("{\"author\":\"test\",\"message\":\"test\"}"));
}
@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
logger.info("Received: " + message + " (" + ClientConfiguration.this.latch.getCount() + ")");
session.close();
ClientConfiguration.this.messagePayload.set(message.getPayload());
ClientConfiguration.this.latch.countDown();
}
};
}
}
}

@ -1,44 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<!-- Your own application should inherit from spring-boot-starter-parent -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-samples</artifactId>
<version>${revision}</version>
</parent>
<artifactId>spring-boot-sample-batch</artifactId>
<name>Spring Boot Batch Sample</name>
<description>Spring Boot Batch Sample</description>
<properties>
<main.basedir>${basedir}/../..</main.basedir>
</properties>
<dependencies>
<!-- Compile -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-batch</artifactId>
</dependency>
<!-- Runtime -->
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<scope>runtime</scope>
</dependency>
<!-- Test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

@ -1,71 +0,0 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.batch;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
@EnableBatchProcessing
public class SampleBatchApplication {
@Autowired
private JobBuilderFactory jobs;
@Autowired
private StepBuilderFactory steps;
@Bean
protected Tasklet tasklet() {
return new Tasklet() {
@Override
public RepeatStatus execute(StepContribution contribution, ChunkContext context) {
return RepeatStatus.FINISHED;
}
};
}
@Bean
public Job job() throws Exception {
return this.jobs.get("job").start(step1()).build();
}
@Bean
protected Step step1() throws Exception {
return this.steps.get("step1").tasklet(tasklet()).build();
}
public static void main(String[] args) {
// System.exit is common for Batch applications since the exit code can be used to
// drive a workflow
System.exit(SpringApplication.exit(SpringApplication.run(SampleBatchApplication.class, args)));
}
}

@ -1,37 +0,0 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.batch;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.test.system.CapturedOutput;
import org.springframework.boot.test.system.OutputCaptureExtension;
import static org.assertj.core.api.Assertions.assertThat;
@ExtendWith(OutputCaptureExtension.class)
class SampleBatchApplicationTests {
@Test
void testDefaultSettings(CapturedOutput capturedOutput) {
assertThat(SpringApplication.exit(SpringApplication.run(SampleBatchApplication.class))).isEqualTo(0);
assertThat(capturedOutput).contains("completed with the following parameters");
}
}

@ -1,126 +0,0 @@
= Spring Boot Cache Sample
This sample demonstrates the caching auto-configuration support. Spring's caching
abstraction is supported by many caching libraries, including:
* Any compliant `JSR-107` (JCache) provider
* `EhCache`
* `Hazelcast`
* `Infinispan`
* `Couchbase`
* `Redis`
* `Caffeine`
* Simple provider based on `ConcurrentHashMap`
* Generic provider based on `org.springframework.Cache` bean definition(s)
The sample defines a simple `CountryService` that caches countries by ISO code. When
the application starts a client invokes the service with a random code every 500ms.
You can look at the `/metrics` endpoint to review the cache statistics if your chosen
caching provider is supported.
== Using the JSR-107 annotations
The sample uses Spring's cache annotation. If you want to use the JSR-107 annotations
instead, simply add the `javax.cache:cache-api` dependency to the project. No further
configuration is necessary.
NOTE: You can use the JSR-107 annotations with _any_ cache provider; a JSR-107
compliant cache provider is not necessary.
== Using a different cache provider
Initially, the project does not define any caching library so the abstraction works
on simple `ConcurrentHashMap`-based caches. You can try out your favorite caching
library as explained below.
=== JCache (JSR-107)
If you want to configure your cache infrastructure via the standard, you need a
compliant implementation and the JSR-107 api. You first need to add
`javax.cache:cache-api` to your project. Then you could try the following:
* `EhCache 3`: add `org.ehcache:ehcache`
* `Hazelcast`: add `com.hazelcast:hazelcast`
* `Infinispan`: add `org.infinispan:infinispan-jcache`
TIP: Run sample cache application using JCache and EhCache3 by uncommenting the
`spring.cache.jcache.config` property and `$mvn spring-boot:run -Pehcache`.
TIP: Refer to the documentation of the JSR-107 implementation you want to use: certain
cache providers do not create a default cache on-the-fly if it does not exist so you might
need to update the sample to create the caches on startup or specify the location to the
provider-specific file via the `spring.cache.jcache.config` property.
NOTE: Any other JSR-107 compliant provider is also supported but Spring Boot may not
offer a dependency management entry for it. You will have to add it with the version
of the library that you want to use.
=== EhCache 2.x
Simply add the `net.sf.ehcache:ehcache` dependency to the project. Since there is a
default `ehcache.xml` configuration file at the root of the classpath,
it is automatically used to configure the underlying `CacheManager`.
Note that EhCache 3 uses a different format and doesn't default to `ehcache.xml`
anymore. Check https://www.ehcache.org/documentation/3.0/xml.html[the documentation]
for more details.
TIP: Run sample cache application using EhCache with
`$mvn spring-boot:run -Pehcache2`.
=== Hazelcast
Both `com.hazelcast:hazelcast` and `com.hazelcast:hazelcast-spring` should be added
to the project to enable support for Hazelcast. Since there is a default
`hazelcast.xml` configuration file at the root of the classpath, it is used to
automatically configure the underlying `HazelcastInstance`.
TIP: Run sample cache application using Hazelcast with
`$mvn spring-boot:run -Phazelcast`.
=== Infinispan
Add the `org.infinispan:infinispan-spring4-embedded` dependency to enable support for
Infinispan. There is no default location that Infinispan uses to look for a config
file so this sample is configured to use the provider `infinispan.xml` configuration
file specified via the `spring.cache.infinispan.config` property.
TIP: Run sample cache application using Infinispan with
`$mvn spring-boot:run -Pinfinispan`.
NOTE: If you want to use the client/server mode or if you need more options, Infinispan
provides an official Spring Boot starter, check
https://github.com/infinispan/infinispan-spring-boot[the documentation] for more details.
=== Couchbase
Add the `java-client` and `couchbase-spring-cache` dependencies and make sure that
you have setup at least a `spring.couchbase.bootstrap-hosts` property.
TIP: Run sample cache application using Couchbase with
`$mvn spring-boot:run -Pcouchbase`.
=== Redis
Add the `spring-boot-starter-data-redis` and make sure it is configured properly (by
default, a redis instance with the default settings is expected on your local box).
TIP: Run sample cache application using Redis with
`$mvn spring-boot:run -Predis`.
=== Caffeine
Simply add the `com.github.ben-manes.caffeine:caffeine` dependency to enable support
for Caffeine. You can customize how caches are created in different ways, see
`application.properties` for an example and the documentation for more details.
TIP: Run sample cache application using Caffeine with
`$mvn spring-boot:run -Pcaffeine`.

@ -1,128 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<!-- Your own application should inherit from spring-boot-starter-parent -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-samples</artifactId>
<version>${revision}</version>
</parent>
<artifactId>spring-boot-sample-cache</artifactId>
<name>Spring Boot Cache Sample</name>
<description>Spring Boot Cache Sample</description>
<properties>
<main.basedir>${basedir}/../..</main.basedir>
</properties>
<dependencies>
<!-- Compile -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<!-- Only used to expose cache metrics -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!-- Test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>caffeine</id>
<dependencies>
<dependency>
<groupId>com.github.ben-manes.caffeine</groupId>
<artifactId>caffeine</artifactId>
</dependency>
</dependencies>
</profile>
<profile>
<id>couchbase</id>
<dependencies>
<dependency>
<groupId>com.couchbase.client</groupId>
<artifactId>java-client</artifactId>
</dependency>
<dependency>
<groupId>com.couchbase.client</groupId>
<artifactId>couchbase-spring-cache</artifactId>
</dependency>
</dependencies>
</profile>
<profile>
<id>ehcache2</id>
<dependencies>
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
</dependency>
</dependencies>
</profile>
<profile>
<id>ehcache</id>
<dependencies>
<dependency>
<groupId>javax.cache</groupId>
<artifactId>cache-api</artifactId>
</dependency>
<dependency>
<groupId>org.ehcache</groupId>
<artifactId>ehcache</artifactId>
</dependency>
</dependencies>
</profile>
<profile>
<id>hazelcast</id>
<dependencies>
<dependency>
<groupId>com.hazelcast</groupId>
<artifactId>hazelcast</artifactId>
</dependency>
<dependency>
<groupId>com.hazelcast</groupId>
<artifactId>hazelcast-spring</artifactId>
</dependency>
</dependencies>
</profile>
<profile>
<id>infinispan</id>
<dependencies>
<dependency>
<groupId>org.infinispan</groupId>
<artifactId>infinispan-spring4-embedded</artifactId>
</dependency>
<dependency>
<groupId>org.infinispan</groupId>
<artifactId>infinispan-jcache</artifactId>
</dependency>
</dependencies>
</profile>
<profile>
<id>redis</id>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
</dependencies>
</profile>
</profiles>
</project>

@ -1,44 +0,0 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.cache;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.cache.CacheManager;
import org.springframework.stereotype.Component;
@Component
public class CacheManagerCheck implements CommandLineRunner {
private static final Log logger = LogFactory.getLog(CacheManagerCheck.class);
private final CacheManager cacheManager;
public CacheManagerCheck(CacheManager cacheManager) {
this.cacheManager = cacheManager;
}
@Override
public void run(String... strings) throws Exception {
logger.info("\n\n" + "=========================================================\n" + "Using cache manager: "
+ this.cacheManager.getClass().getName() + "\n"
+ "=========================================================\n\n");
}
}

@ -1,53 +0,0 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.cache;
import java.io.Serializable;
@SuppressWarnings("serial")
public class Country implements Serializable {
private final String code;
public Country(String code) {
this.code = code;
}
public String getCode() {
return this.code;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Country country = (Country) o;
return this.code.equals(country.code);
}
@Override
public int hashCode() {
return this.code.hashCode();
}
}

@ -1,33 +0,0 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.cache;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;
@Component
@CacheConfig(cacheNames = "countries")
public class CountryRepository {
@Cacheable
public Country findByCode(String code) {
System.out.println("---> Loading country with code '" + code + "'");
return new Country(code);
}
}

@ -1,33 +0,0 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.cache;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.scheduling.annotation.EnableScheduling;
@EnableCaching
@EnableScheduling
@SpringBootApplication
public class SampleCacheApplication {
public static void main(String[] args) {
new SpringApplicationBuilder().sources(SampleCacheApplication.class).profiles("app").run(args);
}
}

@ -1,63 +0,0 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.cache;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import org.springframework.context.annotation.Profile;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
@Profile("app")
class SampleClient {
private static final List<String> SAMPLE_COUNTRY_CODES = Arrays.asList("AF", "AX", "AL", "DZ", "AS", "AD", "AO",
"AI", "AQ", "AG", "AR", "AM", "AW", "AU", "AT", "AZ", "BS", "BH", "BD", "BB", "BY", "BE", "BZ", "BJ", "BM",
"BT", "BO", "BQ", "BA", "BW", "BV", "BR", "IO", "BN", "BG", "BF", "BI", "KH", "CM", "CA", "CV", "KY", "CF",
"TD", "CL", "CN", "CX", "CC", "CO", "KM", "CG", "CD", "CK", "CR", "CI", "HR", "CU", "CW", "CY", "CZ", "DK",
"DJ", "DM", "DO", "EC", "EG", "SV", "GQ", "ER", "EE", "ET", "FK", "FO", "FJ", "FI", "FR", "GF", "PF", "TF",
"GA", "GM", "GE", "DE", "GH", "GI", "GR", "GL", "GD", "GP", "GU", "GT", "GG", "GN", "GW", "GY", "HT", "HM",
"VA", "HN", "HK", "HU", "IS", "IN", "ID", "IR", "IQ", "IE", "IM", "IL", "IT", "JM", "JP", "JE", "JO", "KZ",
"KE", "KI", "KP", "KR", "KW", "KG", "LA", "LV", "LB", "LS", "LR", "LY", "LI", "LT", "LU", "MO", "MK", "MG",
"MW", "MY", "MV", "ML", "MT", "MH", "MQ", "MR", "MU", "YT", "MX", "FM", "MD", "MC", "MN", "ME", "MS", "MA",
"MZ", "MM", "NA", "NR", "NP", "NL", "NC", "NZ", "NI", "NE", "NG", "NU", "NF", "MP", "NO", "OM", "PK", "PW",
"PS", "PA", "PG", "PY", "PE", "PH", "PN", "PL", "PT", "PR", "QA", "RE", "RO", "RU", "RW", "BL", "SH", "KN",
"LC", "MF", "PM", "VC", "WS", "SM", "ST", "SA", "SN", "RS", "SC", "SL", "SG", "SX", "SK", "SI", "SB", "SO",
"ZA", "GS", "SS", "ES", "LK", "SD", "SR", "SJ", "SZ", "SE", "CH", "SY", "TW", "TJ", "TZ", "TH", "TL", "TG",
"TK", "TO", "TT", "TN", "TR", "TM", "TC", "TV", "UG", "UA", "AE", "GB", "US", "UM", "UY", "UZ", "VU", "VE",
"VN", "VG", "VI", "WF", "EH", "YE", "ZM", "ZW");
private final CountryRepository countryService;
private final Random random;
SampleClient(CountryRepository countryService) {
this.countryService = countryService;
this.random = new Random();
}
@Scheduled(fixedDelay = 500)
public void retrieveCountry() {
String randomCode = SAMPLE_COUNTRY_CODES.get(this.random.nextInt(SAMPLE_COUNTRY_CODES.size()));
System.out.println("Looking for country with code '" + randomCode + "'");
this.countryService.findByCode(randomCode);
}
}

@ -1,47 +0,0 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.cache;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import static org.assertj.core.api.Assertions.assertThat;
@SpringBootTest
class SampleCacheApplicationTests {
@Autowired
private CacheManager cacheManager;
@Autowired
private CountryRepository countryRepository;
@Test
void validateCache() {
Cache countries = this.cacheManager.getCache("countries");
assertThat(countries).isNotNull();
countries.clear(); // Simple test assuming the cache is empty
assertThat(countries.get("BE")).isNull();
Country be = this.countryRepository.findByCode("BE");
assertThat((Country) countries.get("BE").get()).isEqualTo(be);
}
}

@ -1,114 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<!-- Your own application should inherit from spring-boot-starter-parent -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-samples</artifactId>
<version>${revision}</version>
</parent>
<artifactId>spring-boot-sample-custom-layout</artifactId>
<name>Spring Boot Custom Layout Sample</name>
<description>Spring Boot Custom Layout Sample</description>
<properties>
<main.basedir>${basedir}/../..</main.basedir>
</properties>
<dependencies>
<!-- Compile -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-loader-tools</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-invoker-plugin</artifactId>
<configuration>
<localRepositoryPath>${project.build.directory}/local-repo</localRepositoryPath>
</configuration>
<executions>
<execution>
<id>prepare-integration-test</id>
<phase>pre-integration-test</phase>
<goals>
<goal>install</goal>
</goals>
</execution>
<execution>
<id>integration-test</id>
<phase>integration-test</phase>
<goals>
<goal>run</goal>
</goals>
<configuration>
<cloneProjectsTo>${project.build.directory}/it</cloneProjectsTo>
<settingsFile>src/it/settings.xml</settingsFile>
<postBuildHookScript>verify</postBuildHookScript>
<addTestClassPath>true</addTestClassPath>
<skipInvocation>${skipTests}</skipInvocation>
<streamLogs>true</streamLogs>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-antrun-plugin</artifactId>
<executions>
<execution>
<id>cleanup-local-integration-repo</id>
<phase>pre-integration-test</phase>
<goals>
<goal>run</goal>
</goals>
<configuration>
<target>
<replaceregexp match="\$\{revision\}" replace="${project.version}"
flags="g" byline="true">
<fileset
dir="${project.build.directory}/local-repo/org/springframework/boot/"
includes="**/*.pom" />
</replaceregexp>
</target>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-failsafe-plugin</artifactId>
</plugin>
</plugins>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.eclipse.m2e</groupId>
<artifactId>lifecycle-mapping</artifactId>
<version>1.0.0</version>
<configuration>
<lifecycleMappingMetadata>
<pluginExecutions>
<pluginExecution>
<pluginExecutionFilter>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<versionRange>[2.10,)</versionRange>
<goals>
<goal>copy</goal>
</goals>
</pluginExecutionFilter>
<action>
<ignore></ignore>
</action>
</pluginExecution>
</pluginExecutions>
</lifecycleMappingMetadata>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>

@ -1,43 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.springframework.boot.maven.it</groupId>
<artifactId>custom</artifactId>
<version>0.0.1.BUILD-SNAPSHOT</version>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>@project.version@</version>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
<configuration>
<layoutFactory implementation="sample.layout.SampleLayoutFactory">
<name>custom</name>
</layoutFactory>
</configuration>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>@project.groupId@</groupId>
<artifactId>@project.artifactId@</artifactId>
<version>@project.version@</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
<dependencies>
</dependencies>
</project>

@ -1,6 +0,0 @@
import java.io.*;
import sample.layout.*;
Verify.verify(
new File(basedir, "target/custom-0.0.1.BUILD-SNAPSHOT.jar"), "custom"
)

@ -1,6 +0,0 @@
import java.io.*;
import sample.layout.*;
Verify.verify(
new File(basedir, "target/default-0.0.1.BUILD-SNAPSHOT.jar"), "sample"
)

@ -1,35 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<settings>
<profiles>
<profile>
<id>it-repo</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<repositories>
<repository>
<id>local.central</id>
<url>@localRepositoryUrl@</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>local.central</id>
<url>@localRepositoryUrl@</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>true</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
</profile>
</profiles>
</settings>

@ -1,44 +0,0 @@
/*
* Copyright 2012-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.layout;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import org.springframework.boot.loader.tools.CustomLoaderLayout;
import org.springframework.boot.loader.tools.Layouts;
import org.springframework.boot.loader.tools.LoaderClassesWriter;
/**
* An example layout.
*
* @author Phillip Webb
*/
public class SampleLayout extends Layouts.Jar implements CustomLoaderLayout {
private String name;
public SampleLayout(String name) {
this.name = name;
}
@Override
public void writeLoadedClasses(LoaderClassesWriter writer) throws IOException {
writer.writeEntry(this.name, new ByteArrayInputStream("test".getBytes()));
}
}

@ -1,48 +0,0 @@
/*
* Copyright 2012-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.layout;
import java.io.File;
import org.springframework.boot.loader.tools.Layout;
import org.springframework.boot.loader.tools.LayoutFactory;
public class SampleLayoutFactory implements LayoutFactory {
private String name = "sample";
public SampleLayoutFactory() {
}
public SampleLayoutFactory(String name) {
this.name = name;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
@Override
public Layout getLayout(File source) {
return new SampleLayout(this.name);
}
}

@ -1,2 +0,0 @@
org.springframework.boot.loader.tools.LayoutFactory=\
sample.layout.SampleLayoutFactory

@ -1,41 +0,0 @@
/*
* Copyright 2012-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.layout;
import java.io.File;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
public final class Verify {
private Verify() {
}
public static void verify(File file, String entry) throws Exception {
try (ZipFile zipFile = new ZipFile(file)) {
Enumeration<? extends ZipEntry> entries = zipFile.entries();
while (entries.hasMoreElements()) {
if (entries.nextElement().getName().equals(entry)) {
return;
}
}
throw new AssertionError("No entry " + entry);
}
}
}

@ -1,12 +0,0 @@
= Spring Boot Sample Data Cassandra
To run the project, need to run below `cql` commands on Cassandra.
== Keyspace Creation in Cassandra
[source,indent=0]
----
CREATE KEYSPACE mykeyspace WITH REPLICATION = { 'class' : 'SimpleStrategy', 'replication_factor' : 1 };
----
== Table Creation in Cassandra
Run `cql` using the link:src/test/resources/setup.cql[setup script] located in resources folder.

@ -1,131 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<!-- Your own application should inherit from spring-boot-starter-parent -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-samples</artifactId>
<version>${revision}</version>
</parent>
<artifactId>spring-boot-sample-data-cassandra</artifactId>
<name>Spring Boot Data Cassandra Sample</name>
<description>Spring Boot Data Cassandra Sample</description>
<properties>
<main.basedir>${basedir}/../..</main.basedir>
</properties>
<dependencies>
<!-- Compile -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-cassandra</artifactId>
</dependency>
<!-- Test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.cassandraunit</groupId>
<artifactId>cassandra-unit-spring</artifactId>
<version>3.5.0.1</version>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<executions>
<execution>
<id>reserve-cassandra-port</id>
<goals>
<goal>reserve-network-port</goal>
</goals>
<phase>process-resources</phase>
<configuration>
<portNames>
<portName>cassandra.port.native-transport</portName>
<portName>cassandra.port.storage</portName>
</portNames>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<systemPropertyVariables>
<spring.data.cassandra.port>${cassandra.port.native-transport}</spring.data.cassandra.port>
<cassandra.native_transport_port>${cassandra.port.native-transport}</cassandra.native_transport_port>
<cassandra.storage_port>${cassandra.port.storage}</cassandra.storage_port>
</systemPropertyVariables>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.eclipse.m2e</groupId>
<artifactId>lifecycle-mapping</artifactId>
<version>1.0.0</version>
<configuration>
<lifecycleMappingMetadata>
<pluginExecutions>
<pluginExecution>
<pluginExecutionFilter>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<versionRange>[1.9.1,)</versionRange>
<goals>
<goal>reserve-network-port</goal>
</goals>
</pluginExecutionFilter>
<action>
<ignore />
</action>
</pluginExecution>
</pluginExecutions>
</lifecycleMappingMetadata>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
<profiles>
<profile>
<id>java9+</id>
<activation>
<jdk>[9,)</jdk>
</activation>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<skipTests>true</skipTests>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
</project>

@ -1,48 +0,0 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.data.cassandra;
import java.util.UUID;
import org.springframework.data.cassandra.core.mapping.PrimaryKey;
import org.springframework.data.cassandra.core.mapping.Table;
@Table
public class Customer {
@PrimaryKey
private UUID id;
private String firstName;
private String lastName;
public Customer() {
}
public Customer(UUID id, String firstName, String lastName) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
}
@Override
public String toString() {
return String.format("Customer[id=%s, firstName='%s', lastName='%s']", this.id, this.firstName, this.lastName);
}
}

@ -1,32 +0,0 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.data.cassandra;
import java.util.List;
import org.springframework.data.cassandra.repository.Query;
import org.springframework.data.repository.CrudRepository;
public interface CustomerRepository extends CrudRepository<Customer, String> {
@Query("Select * from customer where firstname=?0")
Customer findByFirstName(String firstName);
@Query("Select * from customer where lastname=?0")
List<Customer> findByLastName(String lastName);
}

@ -1,64 +0,0 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.data.cassandra;
import com.datastax.driver.core.utils.UUIDs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SampleCassandraApplication implements CommandLineRunner {
@Autowired
private CustomerRepository repository;
@Override
public void run(String... args) throws Exception {
this.repository.deleteAll();
// save a couple of customers
this.repository.save(new Customer(UUIDs.timeBased(), "Alice", "Smith"));
this.repository.save(new Customer(UUIDs.timeBased(), "Bob", "Smith"));
// fetch all customers
System.out.println("Customers found with findAll():");
System.out.println("-------------------------------");
for (Customer customer : this.repository.findAll()) {
System.out.println(customer);
}
System.out.println();
// fetch an individual customer
System.out.println("Customer found with findByFirstName('Alice'):");
System.out.println("--------------------------------");
System.out.println(this.repository.findByFirstName("Alice"));
System.out.println("Customers found with findByLastName('Smith'):");
System.out.println("--------------------------------");
for (Customer customer : this.repository.findByLastName("Smith")) {
System.out.println(customer);
}
}
public static void main(String[] args) {
SpringApplication.run(SampleCassandraApplication.class, args);
}
}

@ -1,44 +0,0 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.data.cassandra;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.cassandraunit.spring.CassandraUnitDependencyInjectionTestExecutionListener;
import org.springframework.core.Ordered;
public class OrderedCassandraTestExecutionListener extends CassandraUnitDependencyInjectionTestExecutionListener {
private static final Log logger = LogFactory.getLog(OrderedCassandraTestExecutionListener.class);
@Override
public int getOrder() {
return Ordered.HIGHEST_PRECEDENCE;
}
@Override
protected void cleanServer() {
try {
super.cleanServer();
}
catch (Exception ex) {
logger.warn("Failure during server cleanup", ex);
}
}
}

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save