{{announcement.body}}
{{announcement.title}}

Hello World Groovy in the Cloud With Spring

DZone 's Guide to

Hello World Groovy in the Cloud With Spring

In this tutorial, we are going to look at Groovy using Spring MVC and MongoDB.

· Java Zone ·
Free Resource

In this tutorial, we are going to look at Groovy using Spring MVC and MongoDB.

The first step is to create a Gradle project that uses Groovy. The easiest way to bootstrap a Spring Boot Maven project is by using Spring Initializer.

If you are familiar with Maven, we might be surprised how it is possible to do the same thing with less line of configuration.

Groovy
 




x
29


 
1
plugins {
2
    id 'org.springframework.boot' version '2.3.3.RELEASE'
3
    id 'io.spring.dependency-management' version '1.0.10.RELEASE'
4
    id 'groovy'
5
}
6
 
          
7
group = 'sh.platform.template'
8
version = '0.0.1-SNAPSHOT'
9
sourceCompatibility = '11'
10
 
          
11
repositories {
12
    mavenCentral()
13
}
14
 
          
15
dependencies {
16
    implementation 'org.springframework.boot:spring-boot-starter-data-mongodb'
17
    implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
18
    implementation 'org.springframework.boot:spring-boot-starter-validation'
19
    implementation 'org.springframework.boot:spring-boot-starter-web'
20
    implementation 'org.codehaus.groovy:groovy'
21
    testImplementation('org.springframework.boot:spring-boot-starter-test') {
22
        exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
23
    }
24
}
25
 
          
26
test {
27
    useJUnitPlatform()
28
}
29
 
          



Our sample we'll use MongoDB, If you want to run MongoDB locally, a good option might be Docker, which you can run with the command below:

Shell
 




xxxxxxxxxx
1


 
1
docker run -d --name mongodb-instance -p 27017:27017 mongo



In this project, we’ll create a sample that will handle a user in its respective client. The first step is to create the entity class, in this sample, a User class.

Groovy
 




x


 
1
import org.springframework.data.annotation.Id
2
import org.springframework.data.mongodb.core.mapping.Document
3
 
          
4
import javax.validation.constraints.NotBlank
5
 
          
6
@Document
7
class User {
8
 
          
9
    @Id
10
    String id;
11
 
          
12
    @NotBlank(message = "Name is mandatory")
13
    String name;
14
 
          
15
    @NotBlank(message = "Language is mandatory")
16
    String language;
17
 
          
18
}



The repository interface makes the integration between the Scala application and the MongoDB instance easy:

Groovy
 




x


 
1
import org.springframework.data.repository.CrudRepository;
2
import org.springframework.stereotype.Repository;
3
 
          
4
@Repository
5
interface UserRepository extends CrudRepository<User, String> {
6
 
          
7
}



The last step is to create a resource where the client can do the request and then the CRUD:

Groovy
 




xxxxxxxxxx
1
68


 
1
import org.springframework.beans.factory.annotation.Autowired;
2
import org.springframework.stereotype.Controller;
3
import org.springframework.ui.Model;
4
import org.springframework.validation.BindingResult;
5
import org.springframework.web.bind.annotation.GetMapping;
6
import org.springframework.web.bind.annotation.PathVariable;
7
import org.springframework.web.bind.annotation.PostMapping;
8
 
          
9
import javax.validation.Valid;
10
 
          
11
 
          
12
@Controller
13
class UserController {
14
 
          
15
    @Autowired
16
    private UserRepository userRepository;
17
 
          
18
    @GetMapping("/")
19
    String start(Model model) {
20
        model.addAttribute("users", userRepository.findAll());
21
        return "index";
22
    }
23
 
          
24
    @GetMapping("/signup")
25
    String showSignUpForm(User user) {
26
        return "add-user";
27
    }
28
 
          
29
    @PostMapping("/adduser")
30
    String addUser(@Valid User user, BindingResult result, Model model) {
31
        if (result.hasErrors()) {
32
            return "add-user";
33
        }
34
 
          
35
        userRepository.save(user);
36
        model.addAttribute("users", userRepository.findAll());
37
        return "index";
38
    }
39
 
          
40
    @GetMapping("/edit/{id}")
41
    String showUpdateForm(@PathVariable("id") String id, Model model) {
42
        User user = userRepository.findById(id).orElseThrow({ ->
43
            new IllegalArgumentException("Invalid user Id:" + id) });
44
        model.addAttribute("user", user);
45
        return "update-user";
46
    }
47
 
          
48
    @PostMapping("/update/{id}")
49
    String updateUser(@PathVariable("id") String id, @Valid User user, BindingResult result, Model model) {
50
        if (result.hasErrors()) {
51
            user.setId(id);
52
            return "update-user";
53
        }
54
 
          
55
        userRepository.save(user);
56
        model.addAttribute("users", userRepository.findAll());
57
        return "index";
58
    }
59
 
          
60
    @GetMapping("/delete/{id}")
61
    String deleteUser(@PathVariable("id") String id, Model model) {
62
        User user = userRepository.findById(id).orElseThrow({ ->
63
            new IllegalArgumentException("Invalid user Id:" + id) });
64
        userRepository.delete(user);
65
        model.addAttribute("users", userRepository.findAll());
66
        return "index";
67
    }
68
}



To run the Java application left the startup class, where we define it as a boot app.

Groovy
 




xxxxxxxxxx
1
11


 
1
import org.springframework.boot.SpringApplication
2
import org.springframework.boot.autoconfigure.SpringBootApplication
3
 
          
4
@SpringBootApplication
5
class GroovyApplication {
6
 
          
7
    static void main(String[] args) {
8
        SpringApplication.run(GroovyApplication, args)
9
    }
10
 
          
11
}



In the front-end site thymeleaf parses the HTML templates and evaluates all expressions to render the value that was set in the controller:

HTML
 




xxxxxxxxxx
1
44


 
1
<!DOCTYPE html>
2
<html xmlns:th="http://www.thymeleaf.org">
3
<head>
4
    <meta charset="utf-8">
5
    <meta http-equiv="x-ua-compatible" content="ie=edge">
6
    <title>Users</title>
7
    <meta name="viewport" content="width=device-width, initial-scale=1">
8
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
9
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.4.1/css/all.css" integrity="sha384-5sAR7xN1Nv6T6+dT2mhtzEpVJvfS3NScPQTrOxhwjIuvcA67KV2R5Jz6kr4abQsz" crossorigin="anonymous">
10
    <link rel="stylesheet" href="../css/shards.min.css">
11
</head>
12
<body>
13
<div th:switch="${users}" class="container my-5">
14
    <div class="row">
15
        <div class="col-md-6">
16
            <h2 th:case="null">No users yet!</h2>
17
            <div th:case="*">
18
                <h2 class="my-5">Users</h2>
19
                <table class="table table-striped table-responsive-md">
20
                    <thead>
21
                    <tr>
22
                        <th>Name</th>
23
                        <th>Language</th>
24
                        <th>Edit</th>
25
                        <th>Delete</th>
26
                    </tr>
27
                    </thead>
28
                    <tbody>
29
                    <tr th:each="user : ${users}">
30
                        <td th:text="${user.name}"></td>
31
                        <td th:text="${user.language}"></td>
32
                        <td><a th:href="@{/edit/{id}(id=${user.id})}" class="btn btn-primary"><i class="fas fa-user-edit ml-2"></i></a></td>
33
                        <td><a th:href="@{/delete/{id}(id=${user.id})}" class="btn btn-primary"><i class="fas fa-user-times ml-2"></i></a></td>
34
                    </tr>
35
                    </tbody>
36
                </table>
37
            </div>
38
            <p class="my-5"><a href="/signup" class="btn btn-primary"><i class="fas fa-user-plus ml-2"></i></a></p>
39
        </div>
40
    </div>
41
</div>
42
</body>
43
</html>
44
 
          


The Java application is ready to go! Let's move it to the cloud easily with Platform.sh from three three YAML files:

1) Route:

YAML
 




xxxxxxxxxx
1


1
"https://{default}/":
2
  type: upstream
3
  upstream: "app:http"
4
 
          
5
"https://www.{default}/":
6
  type: redirect
7
  to: "https://{default}/"


2) Service

YAML
 




xxxxxxxxxx
1


 
1
db:
2
    type: mongodb:3.6
3
    disk: 1024
4
 
          


3) Application

YAML
 




xxxxxxxxxx
1
10


1
name: app
2
type: "java:11"
3
disk: 1024
4
hooks:
5
    build: mvn clean package
6
relationships:
7
    database: "db:mongodb"
8
web:
9
    commands:
10
        start: java -jar $JAVA_OPTS $CREDENTIAL -Dserver.port=$PORT target/spring-scala-mongodb.jar



The application is now ready, so it’s time to move it to the cloud with Platform.sh using the following steps:

  • Create a new free trial account.
  • Sign up with a new user and password, or login using a current GitHub, Bitbucket, or Google account. If you use a third-party login, you’ll be able to set a password for your Platform.sh account later.
  • Select the region of the world where your site should live.
  • Select the blank template.

You have the option to either integrate to GitHub, GitLab, or Platform.sh will provide to you. Finally, push to the remote repository.

Done! We have a simple and nice Spring Groovy application ready to go to the cloud.

Topics:
cloud, groovy, java, platform.sh, spring, tutorial

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}