accessing the spring-restdocs generated content in a spring boot application - spring-boot

I'm using Spring Restdocs (v1.1.2) in a Spring Boot (v1.4.1) application.
In the jar task of the Gradle build file, I'm copying the generated output into public/docs:
jar {
dependsOn asciidoctor
from ("${asciidoctor.outputDir}/html5") {
into 'public/docs'
}
}
and I see in the generated JAR the document in
BOOT-INF/classes/public/docs/api-guide.html
However, when I run the JAR, I can't seem to address the api-guide.html at /docs, /public/docs, etc.
Can someone please explain what I'm doing wrong?
Thanks!
--john
buildscript {
ext {
springBootVersion = '1.4.1.RELEASE'
}
}
plugins {
id "org.asciidoctor.convert" version "1.5.3"
}
apply plugin: 'groovy'
apply plugin: 'spring-boot'
ext {
snippetsDir = file('build/generated-snippets')
springRestdocsVersion = '1.1.2.RELEASE'
}
test {
outputs.dir snippetsDir
}
asciidoctor {
attributes 'snippets': snippetsDir
inputs.dir snippetsDir
dependsOn test
}
jar {
dependsOn asciidoctor
from ("${asciidoctor.outputDir}/html5") {
into 'public/docs'
}
}
dependencies {
compile('org.springframework.boot:spring-boot-starter-data-rest')
testCompile("org.springframework.restdocs:spring-restdocs-mockmvc:${springRestdocsVersion}")
}
=============================================================
here's the application config:
#SpringBootApplication
#EnableJpaRepositories
#EnableScheduling
class Application {
static void main(String[] args) {
SpringApplication.run Application, args
}
}
and the test config:
#RunWith(SpringJUnit4ClassRunner)
#SpringApplicationConfiguration(classes = Application)
class ApplicationTests {
...
}

OK, I finally figured out what I was doing wrong. I had the spring-boot-actuator-docs enabled:
compile('org.springframework.boot:spring-boot-actuator-docs')
and it was "taking over" the /docs path. As soon as I relocated the generated restdocs to a different path, e.g.
jar {
dependsOn asciidoctor
from ("${asciidoctor.outputDir}/html5") {
into 'static/api'
}
}
all was good.
Thanks Andy for your interest in my question and the very cool Spring REST Docs project!

Related

Gradle not creating a Tomcat deployable war

I'm running into an issue with building a war with Gradle 4.8.1. Here is the build.gradle:
buildscript {
ext {
springBootVersion = '2.0.3.RELEASE'
}
repositories {
jcenter()
}
dependencies {
classpath "org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}"
}
}
apply plugin: 'idea'
apply plugin: 'io.spring.dependency-management'
apply plugin: 'java'
apply plugin: 'maven'
apply plugin: 'org.springframework.boot'
apply plugin: 'war'
archivesBaseName = 'sample'
//war {
// archiveName = 'sample.war'
// group = 'my.group'
// version = '2.0.0-SNAPSHOT'
//}
sourceCompatibility = 1.8
repositories {
jcenter()
maven { url "${nexusUrl}/content/groups/public" }
}
dependencies {
// Spring
compile 'org.springframework.boot:spring-boot-starter-actuator'
compile 'org.springframework.boot:spring-boot-starter-data-jpa'
compile 'org.springframework.boot:spring-boot-starter-log4j2'
providedRuntime 'org.springframework.boot:spring-boot-starter-tomcat'
compile 'org.springframework.boot:spring-boot-starter-web'
testCompile 'org.springframework.boot:spring-boot-starter-test'
// Lombok
compile "org.projectlombok:lombok:1.18.0"
// Data
compile ('org.postgresql:postgresql') {
exclude module: 'slf4j-simple'
}
// Http
compile "org.apache.httpcomponents:httpclient:4.5.5"
}
configurations {
all*.exclude module: 'spring-boot-starter-logging'
}
uploadArchives {
repositories {
mavenDeployer {
repository(url: "${nexusUrl}/content/groups/public/") {
authentication(userName: nexusUsername, password: nexusPassword)
}
snapshotRepository(url: "${nexusUrl}/content/repositories/snapshots") {
authentication(userName: nexusUsername, password: nexusPassword)
}
pom.version = '2.0.0-SNAPSHOT'
pom.artifactId = 'sample'
pom.groupId = 'my.group'
}
}
}
I also tried removing the 'maven' plugin, archivesBaseName, and the uploadArchive task while uncommenting the war task and I get the same result. When using uploadArchive the war deploys to the nexus server fine and I get no errors. When deploying the war to tomcat (in both instances) tomcat 7 and 8 throw no errors and I receive no logs from either catalina or the project, although archiveName inside the war task does not properly rename the war. I have tried this on two other machines/tomcat instances with the same result. When building this as a fat jar, or running this in IntelliJ, everything works as expected (including the logging).
Any help or direction would be greatly appreciated.
It sounds like it is not initializing the servlet at all. Make sure to extend the SpringBootServletInitializer for WAR deployment.
Spring Boot Docs - Traditional Deployment
I was also facing the same issue. The issue is Spring application doesnt get initialized when the war is deployed on tomcat.
After a lot of struggle, I figured out that I needed to extend SpringBootServletInitializer in my application. So my effective code looks like
public class SyncApplication extends SpringBootServletInitializer {
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(SyncApplication.class);
}
public static void main(String[] args) {
SpringApplication.run(SyncApplication.class, args);
}
}
Looks like this SpringBootServletInitializer directs war plugins generate bootstrapping code while building the war, and thus spring context is initialized while deploying the app.

Gradle build with fatJar plugin and SpringBoot application gives 'Application startup failed'

Everything was working fine when starting my app using Intellij. But when I made fatJar (with gradle plugin: eu.appsatori.fatjar) and execute:
java -jar myapp.jar
I'm getting something like this:
11:41:01.224 [main] ERROR org.springframework.boot.SpringApplication - Application startup failed
org.springframework.beans.factory.BeanDefinitionStoreException: Failed to process import candidates for configuration class [my.testing.MyAppMain]; nested exception is java.lang.IllegalArgumentException: No auto configuration classes found in META-INF/spring.factories. If you are using a custom packaging, make sure that file is correct.
at org.springframework.context.annotation.ConfigurationClassParser.processDeferredImportSelectors(ConfigurationClassParser.java:482)
at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:184)
...
It looks like it didn't found auto configuration classes in META-INF/spring.factories.
How to add this file? And what should be the content of it?
I've got following build script:
apply plugin: "java";
apply plugin: "idea";
apply plugin: 'application'
apply plugin: 'eu.appsatori.fatjar'
apply plugin: 'org.springframework.boot'
repositories {
mavenCentral()
}
buildscript {
ext {
springBootVersion = '1.4.3.RELEASE'
}
repositories {
mavenCentral()
jcenter()
}
dependencies {
classpath "org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}"
classpath "eu.appsatori:gradle-fatjar-plugin:0.3"
}
}
sourceSets {
main {
java {
srcDir 'src/main/java'
}
resources {
srcDir 'src/main/resources'
}
}
test {
java {
srcDir 'src/test/java'
}
}
}
fatJar {
manifest {
attributes("Main-Class": 'my.testing.MyAppMain')
}
exclude 'META-INF/*.DSA'
exclude 'META-INF/*.SF'
exclude 'META-INF/*.RSA'
}
dependencies {
compile 'org.springframework.boot:spring-boot-starter-jdbc'
runtime 'mysql:mysql-connector-java'
testCompile 'org.springframework.boot:spring-boot-starter-test'
}
And my example code is:
package my.testing;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
#SpringBootApplication
public class MyAppMain {
private ConfigurableApplicationContext springContext;
#Autowired
private SimpleDao dao;
public static void main(String[] args) throws Exception {
MyAppMain test = new MyAppMain();
try {
test.init();
test.doWhatYouGotToDo();
} finally {
test.stop();
}
}
private void doWhatYouGotToDo() {
System.out.println("Auto-wired dao: " + dao.hashCode());
System.out.println("Auto-wired jdbcTemplate: " + dao.jdbcTemplate.hashCode());
}
private void init() throws Exception {
springContext = SpringApplication.run(MyAppMain.class);
springContext.getAutowireCapableBeanFactory().autowireBean(this);
}
private void stop() throws Exception {
springContext.close();
}
}
#Component
class SimpleDao {
#Autowired
JdbcTemplate jdbcTemplate;
}
application.properties file:
spring.datasource.driver-class-name = com.mysql.jdbc.Driver
spring.datasource.url = jdbc:mysql://localhost:3306/some_db?useSSL=false&serverTimezone=UTC
spring.datasource.username = some_user
spring.datasource.password = some_pass
NOTE: This question is based on SpringBoot - making jar files - No auto configuration classes found in META-INF/spring.factories
where are all answers are referring to building with Maven. Please put only answers related to Gradle here.
Although I mostly use Maven for Spring and Gradle for Android, but here is the gradle way for a Spring project:
gradle clean build
gradle bootRepackage
Result:
Here is my build.gradle file:

Using Gradle Dependency inside of Custom Plugin

I am trying to write a custom Gradle Plugin that invokes the flyway migration using their API:
https://flywaydb.org/documentation/api/
This is a minimal example:
buildscript {
repositories.jcenter()
dependencies.classpath "org.flywaydb:flyway-core:4.1.2"
}
apply plugin: DatabaseHandlerPlugin
class DatabaseHandlerPlugin implements Plugin<Project> {
void apply(Project project) {
project.task("databaseHandler").doLast {
org.flywaydb.Flyway f = new Flyway(); // <= How can I use the above declared dependency here and in my projects?
}
}
}
But my gradle complains that it cannot load the Flyway class.
The Flyway class is in the org.flywaydb.core package. You missed the core bit. My full code that works:
import org.flywaydb.core.Flyway; // << can import here
buildscript {
repositories { mavenCentral() }
dependencies {
classpath "org.flywaydb:flyway-core:4.1.2"
}
}
apply plugin: DatabaseHandlerPlugin
class DatabaseHandlerPlugin implements Plugin<Project> {
void apply(Project project) {
project.task('databaseHandler') {
doLast {
Flyway f = new Flyway()
println "Flyway: $f"
}
}
}
}
Output:
> gradle databaseHandler
:databaseHandler
Flyway: org.flywaydb.core.Flyway#7b27e8f4

Missing schema module for spring-cloud-stream

Trying to use the following example from Spring Docs
#Bean
public MessageConverter userMessageConverter() throws IOException {
AvroSchemaMessageConverter avroSchemaMessageConverter {
return new AvroSchemaMessageConverter(MimeType.valueOf("avro/bytes");
}
Using Gradle as follows
buildscript {
ext {
springBootVersion = '1.4.2.RELEASE'
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
apply plugin: 'org.springframework.boot'
dependencies {
compile('org.springframework.cloud:spring-cloud-stream')
compile('org.springframework.cloud:spring-cloud-starter-stream-kafka')
}
dependencyManagement {
imports {
mavenBom "org.springframework.cloud:spring-cloud-dependencies:Camden.SR2"
}
}
Gradle is loading the correct version of spring-cloud-streams 1.1.0.RELEASE but it does not match with the Github Repo. The artifact is missing the org.springframework.cloud.stream.schema package/source.
Am I missing something here?
The artifact org.springframework.cloud:spring-cloud-starter-stream-kafka brings in spring-cloud-stream, spring-cloud-stream-codec and related dependencies like spring-integration. You would have to explicitly define org.springframework.cloud:spring-cloud-stream-schema.
Also, you don't need to specify 'org.springframework.cloud:spring-cloud-stream' as it will be part of org.springframework.cloud:spring-cloud-starter-stream-kafka via org.springframework.cloud:spring-cloud-stream-binder-kafka.

spring boot war deployment to tomcat with status:OK But gives 404 on access

My configration class looks as follow
#Configuration
#EnableAutoConfiguration
#ComponentScan(basePackages = "com.projectx")
public class Application extends SpringBootServletInitializer{
public static void main(String[] args) {
SpringApplication.run(applicationClass, args);
}
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application.class);
}
}
Also build.gradle file looks like this
apply plugin: 'java'
sourceCompatibility=1.8
targetCompatibility=1.8
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'spring-boot'
apply plugin: 'war'
mainClassName = 'com.projectx.data.config.Application'
buildscript {
repositories {
maven { url "http://repo.spring.io/libs-release" }
mavenLocal()
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:1.2.1.RELEASE")
}
}
war {
baseName = 'gs-accessing-data-jpa'
version = '0.1.0'
}
repositories {
mavenLocal()
mavenCentral()
maven { url "http://repo.spring.io/libs-release" }
maven { url "https://repository.jboss.org/nexus/content/repositories/releases" }
}
configurations {
providedRuntime
}
dependencies {
compile("org.springframework.boot:spring-boot-starter-web")
providedRuntime("org.springframework.boot:spring-boot-starter-tomcat")
}
So wherever i am deploying this project to tomcat it is showing following error. As I have mate all requirement to convert jar to war in spring not sure what is wrong this my project.
It gives 404 NOT FOUND.(I am using STS 3.6.0 with Gradle plugin)

Resources