2. Build a Spring Boot App - pnguye35/pal-tracker GitHub Wiki

Purpose This lab will walk you through setting up a Java application using Spring Boot and deploying the application to Pivotal Application Service. The single application will evolve into a suite of services and applications. In the spirit of the history of Pivotal Tracker, the suite of applications will include a software project management tool, an application for tracking time, and an application for allocating people to projects.

Learning Outcomes After completing the lab, you will be able to:

Describe how to create runnable Spring Boot application Describe how to create a controller that responds to HTTP requests Use gradle to run gradle tasks Use the Cloud Foundry CLI to push an app Project structure As mentioned, the labs will build up to a fully distributed system. We will start with a single application using Spring Boot. We have chosen Spring Boot because it integrates well with Pivotal Application Service and the Netflix open source libraries for creating and managing distributed systems (i.e. cloud native applications).

Go to the workspace sub-directory of your home directory.

At Pivotal we practice pair programming and rotate pairs quite frequently, usually two to three times per week. Because of this, a developer may be assigned to a different workstation on any given day. To reduce friction, we adopted this standard setup for where all project code is located.

These lab instructions will assume from now on that your code is in this directory.

The pal-tracker codebase contains a local Git repository with the starting points and the solutions for all the labs in this unit. Download the linked zip file and extract the codebase in the ~/workspace directory. The extracted directory will contains a single text file as well as the (hidden) Git files. You will be building up the code in this directory bit by bit, and we have provided reference implementations at each stage identified by tags in the Git repository. Take some time to navigate through the tags and branches using the following command:

git log --graph --decorate --oneline --all You will see start and solution tags for each of the coming labs.

Create a repository called pal-tracker in your GitHub account. Add this repository as a remote called origin of your local repository. You will push all of your work to this repository during the next few labs.

We will start by pushing the initial commit to GitHub, complete with the start and solutions tags.

git push origin master --tags We can then navigate to GitHub and view the solution tags. This is handy when you get stuck during a lab and need a little help.

You can also use GitHub's compare functionality to compare your code to the solution.

We will be using Gradle as our build and dependency management system.

Create a gradle wrapper in the project root directory (~/workspace/pal-tracker) with a gradle-version of 6.0.1 and distribution-type of all.

gradle wrapper --gradle-version 6.0.1 --distribution-type all Finally, create an empty build.gradle file in the same directory.

Bootstrap the application Now that the plumbing of our application is set up, we can begin building a Spring Boot Hello World application.

Open your project in IntelliJ.

On the Import Project from Gradle dialog, if the option to choose a Java version is given, select Java 11 as the Gradle JVM. This will also select Java 11 as the project SDK (File -> Project Structure).

Take a look at the .gitignore file.

This file tells Git to ignore certain files that should not be stored in version control such as:

built artifacts temporary files editor or IDE generated files Hide .gitignore pal-tracker/.gitignore build .gradle .idea *.iml Add a plugins closure to your build.gradle file:

Apply the 2.2.2.RELEASE version of the spring boot gradle plugin.

Apply the 1.0.8.RELEASE version of the Spring Dependency Management plugin

Apply the Java plugin.

Create a repositories closure adding Maven Central to your build.gradle file.

Add a dependencies closure to your build.gradle file, and add a java implementation dependency on the org.springframework.boot:spring-boot-starter-web package.

The resulting Gradle file should look like this:

Hide build.gradle pal-tracker/build.gradle plugins { id 'org.springframework.boot' version '2.2.2.RELEASE' id 'io.spring.dependency-management' version '1.0.8.RELEASE' id 'java' }

repositories { mavenCentral() }

dependencies { implementation 'org.springframework.boot:spring-boot-starter-web' } Add a settings.gradle file with the following contents:

Hide settings.gradle pal-tracker/settings.gradle rootProject.name = "pal-tracker" This will configure the name of your Gradle project which ensures that your jarfile has the correct filename.

Refresh the Gradle project in your IDE so that it picks up your changes.

Create a standard maven directory layout.

Specifically, create a src/main/java directory structure within the pal-tracker directory.

Inside of the source directory, all of your code will go into the io.pivotal.pal.tracker package. Create this package now.

Create a class in the tracker package called PalTrackerApplication and annotate it with @SpringBootApplication.

This annotation enables component scanning, auto configuration, and declares that the class is a configuration class.

Add a main method to the PalTrackerApplication class and tell Spring to run.

This main method executes the Spring Boot SpringApplication.run method which bootstraps the Dependency Injection container, scans the classpath for beans, and starts the application.

The class will look like this:

Hide PalTrackerApplication.java pal-tracker/src/main/java/io/pivotal/pal/tracker/PalTrackerApplication.java package io.pivotal.pal.tracker;

import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication public class PalTrackerApplication {

public static void main(String[] args) {
    SpringApplication.run(PalTrackerApplication.class, args);
}

} Verify the application is set up correctly by running your application.

Using your Gradle wrapper, run the tasks command to find which task to use to run your application locally. Once you find the task, use it to run your application.

If all is well, you will see log output from Spring Boot and a line that says it is listening on port 8080. Navigate to localhost:8080 and see that the application responds. You will see a whitelabel error page with a status code of 404. The application is running but it does not have any controllers. Stop the application with CTRL + C.

Create a controller In the same package we will create a controller class that returns hello when the app receives a GET request at /.

Following labs will go in to more detail about what is happening here, but for now, just follow along.

Create a class called WelcomeController in the tracker package, alongside the main application class .

Annotate WelcomeController with @RestController and write a method that returns the string hello.

The name of the method is not important to Spring, but call it sayHello. Finally, annotate the method with @GetMapping("/").

The controller will look like this:

Hide WelcomeController.java pal-tracker/src/main/java/io/pivotal/pal/tracker/WelcomeController.java package io.pivotal.pal.tracker;

import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController;

@RestController public class WelcomeController {

@GetMapping("/")
public String sayHello() {
    return "hello";
}

} Verify the controller is working correctly by starting the application.

Now visit localhost:8080 to see the hello message.

We now have a small working web application. In the next steps, we will push this application to Pivotal Application Service to get it running on the internet.

CF CLI We interact with Pivotal Application Service is via the Cloud Foundry CLI.

Verify the CLI is installed correctly by running

cf --help which will show a list of available tasks.

To view more information about each task, use the --help flag. For example, use the following command to find more information about the login command:

cf login --help CF target The CF CLI can interact with multiple installations of PAS so we need to target a specific installation (also called a foundation). Targeting means telling our CLI about the API endpoint for a foundation.

Use the login command to log in to your Cloud Foundry foundation's API endpoint.

Verify the CLI has targeted the correct foundation by using the target command.

Deploy In order to push a JVM application to Pivotal Application Service you may use an executable jar file.

Use gradle to build the jar file for your application.

Use the push command to push your code to an application named pal-tracker while making sure that you:

Use the -p flag to specify the jar file to push. Add the appropriate option to generate a random route. Add another option so that it does not start immediately when you push it for the first time. Use the help for the push command if you need to find the right options to use.

You will see the CF CLI upload the jar file.

Set an environment variable to tell the buildpack to use Java 11.

cf set-env pal-tracker JBP_CONFIG_OPEN_JDK_JRE '{ jre: { version: 11.+ } }' Start the application now that the environment variable is set.

cf start pal-tracker Cloud Foundry begins the staging process. Once staging finishes, Cloud Foundry will start your application. Finally, you should see output indicating the URL that Cloud Foundry picked for the application.

Note that if you accidentally set your application to start when you initially pushed it, you will have to use the restage command instead of start. You should be able to explain why this is the case after completing the next module.

Check that the application is running correctly by visiting its URL in a browser and verifying that you see the correct message.

The application that you have built at this point is very simple, but there is now a solid foundation to build upon.

Make a commit with your new changes and push your work to your repository on GitHub.

Submit this assignment Submit the assignment using the cloudNativeDeveloperSimpleApp gradle task from within the existing assignment-submission project directory. It requires you to provide the URL of your application.

For example:

cd ~/workspace/assignment-submission ./gradlew cloudNativeDeveloperSimpleApp -PserverUrl=https://${APP_URL} You will always submit assignments from the assignment-submission project directory going forward so keeping a separate window open for this will make it easier to submit assignments.

Learning Outcomes Now that you have completed the lab, you should be able to:

Describe how to create runnable Spring Boot application Describe how to create a controller that responds to HTTP requests Use gradle to run gradle tasks Use the Cloud Foundry CLI to push an app Extra If you have additional time, explore the dependencies included in the spring-boot-starter-web library. Go to the main Maven repository for Spring Boot web starter, find the version you are using, and navigate to its page. You will see the Maven POM file (in XML format). The section of the file shows the immediate dependencies of the starter, for example:

org.springframework.boot spring-boot-starter 2.2.4.RELEASE compile ... In Gradle syntax that corresponds to:

implementation 'org.springframework.boot:spring-boot-starter:2.2.4.RELEASE' There is a link to the pages for each of these dependencies at the bottom of the scrolling panel at the right of the screen.

Try to write the dependencies closure in the build.gradle file so that your application runs without using any starters.

⚠️ **GitHub.com Fallback** ⚠️