How to Create Spring Boot Rest-Based Application?

How to Create Spring Boot Rest-Based Application?

Introduction: Cloud Foundry is an open source multi-cloud application platform-as-a-Service based for running orchestrated polyglot applications in a public or private Environment. It provides On Demand network access to shared resources like network storage, apps, server, services for easy provisioning and release on demand.

[Polygot’ means here We can work with different languages like Java, .Net, Python etc. on cloud Foundry and Orchestrated’ means Incoordination of systems from logging to Monitoring of applications]

Pivotal Cloud Foundry is owned by Pivotal Software (now joint venture of VMware, EMC, and General Electric.)

Developing a Simple Spring boot – Rest Web Application and deploy into PCF:

Now we are going create a database driven application using Spring-boot and PostgreSQL database. And after development we will push this application to Pivotal Cloud Foundry

Prerequisite:

  • STS/Eclipse you must install to start with. Here I have used STS
  • Basic knowledge of Pivotal Cloud Foundry and its architecture

Step 1: Creating the Spring boot Project

I am going to start from scratch creating a new Spring-boot project and will build upon that.

  • First Create a maven project in STS like the below project structure I have created as below:

  • In the above xml file you can see that I have added PostgreSQL dependency along with the Spring-boot dependencies ([JPA and web starters]: these Starters which Fetches required dependencies for building RESTful/non restful web Applications using Spring MVC and for using Spring Data JPA with Hibernate)

Step 2: Creating the Property File(“application.properties”)

  • So, to connect our application to our PostgreSQL database, I’ve to provide couple of properties and make sure that these are only necessary in my local development environment. In cloud, these are not going to be used.
  • So, in my resources folder, I have created “ Properties” file where I will provide all the required properties for our databased connections.

Step 3: Creating the Model, Controller and Repository classes

  • REST Controller and Entity Class:

In our application, we are going to have a controller and the controller is going to return as an application metadata in our database when we launch our application.

Basically, I am going to use command line runner that initially runs when the application starts up and create a record in my PostgreSQL database and application metadata. And I’m going to create a get-Mapping request controller so that I can get that metadata of my application from my PostgreSQL db.

  • Entity class (ApplicationMeta.java)

  • Inside this Entity we have created 3 fields (id, meta name and meta desc). I am using the ID as primary key where id is nothing but the UUIDs generated automatically through Hibernate’s UUID2 Generator.
  • @GeneratedValue I have used to get the generated ID (UUID). @GeneratedValue annotation references the UUID generator to “ID” attribute and it defines the uuid generator with the use of @GenericGenerator annotation
  • @GenericGeneratorI have used here to map the uuid generator with hibernate session
  • Repository class (ApplicationMetaRepositorjava)
  • Now to make use of the Entity I am going to create a repository so that I can access my PostgreSQL database and have some interaction in Java Development . So, I have created interface “java”

  • Here I have extended JPA repository to make use of our repository method and as the arguments I have provided ApplicationMeta and a String for our ID
  • we created a JPA method here:”findByName()” so that we can find application meta details using its name attribute inside our postgreSQl db

 

  • Rest Controller class (ApplicationMetaController.java)
  • Now move back to main application class and will create a controller there so that we can provide application meta to the users.
  • So, inside our main class i.e. java class, I have created a static class ApplicationMetaController.java and Inside this controller I have auto wired ApplicationMetaRepository.
  • I have used GetMapping and returning ApplicationMeta object as ResponseEntity. In the applicationData() web method, we are going to the meta repository and we simple return the response entity as the ApplicationMeta that we find inside our database.
  • Actually, to have an application data in our application repository in our PostgreSQL db, we have to first create an application metadata when we launch our application. For this purpose, I have implemented java interface and override its run method. Inside our application initiation when our application starts this method is going to be executed and inside this run () method we created application meta object and saved it to the database.

Please find the controller class as below:

  • This all we need for our PostgreSQL database application to bind the PostgreSQL and Pivotal cloud foundry and deploy it to pcf.

Step 4: Binding PostgreSQL Database to App Using Manifest with CLI

  • Creating PostgreSQL Service Instance in PCF:
    • Now we will create our service and put our cloud foundry for postgreSQL. There are several ways to create a service instance in pcf. We can either use CLI or we can just go to dashboard marketplace for that purpose.
    • To show how you can create a service in the market place a service instance for PostgreSQL, I will switch back to my pivotal cloud foundry dashboard and here I am going to navigate to my services tab.

 

  • PCF CLI Installation:
    • Navigate to the below site in browser:

Then choose windows/MAC OS 64bit.

  • After installation then open the terminal and issue command “cf login”. Then it will ask to enter your API endpoint URL, Email and password for login
  • Give the API endpoint> https://api.run.pivotal.io , Email > <”Your email_id “> and Password> <”your_password”>

and then give the space whether you want to opt Development or production

  • PCF Registration in UI(Dashboard):
  • Open the Dashboard: (https://login.run.pivotal.io) and sign up with your required details<Email Id and password>.
  • Then after successful login you will find the below page:

Here click the “Services” tab and then you will find the below screen:

  • Here I am going to click “Add A Service” button and then you will find a search bar and in that you search for “PostgreSQL” and you will find “ElephantSQL” for that.

  • Here click on the “ElephantSQL” and select the free “Tiny Turtle” plan as below:
    • Note: In the above bind option, you can choose to bind to any exiting application which has been already deployed to pcf. In our case we have not still deployed our application, so I have chosen “do not bind”.
    • Then click “Create”. Then you will find that the service instance will get successfully created as below with the given name.

  • So, we can use this service instance name(mypostgreSQL) to bind our application with PostgreSQL service and for doing that we have to create a manifest file for our application.

NOTE: As an alternative through command line using terminal, we can also directly create the service instance with the below command:

cf create-service elephantsql turtle <service_instance_Name>

  • Creating manifest file for PCF Deployment (manifest.yml):
  • Let’s create a manifest file: (Before this please make sure you would have already created your artifact i.e. the jar file using the maven install from STS).
  • When we will issue “cf push” command, then first it looks in the application directory for the manifest file for execution of deployment process.

  • The three dashes (—) notifies the beginning of a manifest file as per the YAML convention. And “Applications:” field here act as a header block under which we should define the application parameters like name, buildpack and memory. There can be many applications block inside an yml file.
  • Here name: going to be our Application name and Path: our Artifact (jar file) path.
  • Buildpack: As it is a java project, so we have given here the java-build pack URL from PCF. This will be used to compile our application for getting executed or prepare for launch our app along with determining the dependencies to be downloaded. Suppose we will not mention the build pack here then it will download all the supported environments and then considers the appropriate one, but this is going to take a longer execution time. So, we should better give the exact build pack url.
  • Memory: Specifying the memory details for our application to run.
  • Services: We added services tag for service binding purpose for the postgreSQL database. The value for this tag is going to be the name of the service instance name that we have already created our instance (i.e. my from ElephantSQL.

Step 5 : Deployment(cf push operation)

Now Let’s run our application inside PCF. Here I am going to open a terminal session and will issue the “cf login” command first with the API endpoint URL, Email id and password. This already I have mentioned in the PCF CLI installation part. Go to the directory of the application where the application files are.

Cloud foundry will create our application and will create a route for it. then it binds our application with that route. (The router component routes the incoming traffic to the cloud controller component)

It’s currently uploading our application source file into pivotal cloud foundry and the PostgreSQL service instance also get bound to the application. After some few seconds our application will get started and you can see the logs in the console with “App started” like below:

Step 6: Test our Application if up and Running after cf push

  • Now let’s go to our pivotal cloud foundry dashboard and go to the Apps tab and you will find that the application is running. Now you can see the below image where it shows “Running”.

Now click on the “SpringPostgreSQL” application to go inside the app then we will find our app up and running using over 300 MB memory and 150 MB of disk space.

Now Navigate to the “route” section and there you will find the route link.

  • Now click on the application route link and will check out if our controller is working properly as we expect. If I click on that then we will get a Spring whitelabel error page like below which confirms that our app is up and running inside PCF:
  • Now To check out our controller, we are going to provide the exact path which we have developed in our code we already covered.

  • Now you can see in the above image that our application is created when we launch our application for the first time and we could get the application meta details from our PostgreSQL database perfectly. In above response we received contains our UID generated from our postgreSQL using Hibernate and our application name is here “MyNewApp” and we have our description “This is a completely new application” which we have set from our code.
  • Now let’s check out our database service instance in our cloud foundry. Now we will go to our pivotal webservices. Go to the “Services” tab and under that you will find ElephantSQL service in the name of “Bound Services” like below image:

Now if we want to check out the data in side our database, then click on the “ElephantSQL” link and then in the next window you will find “Manage” tab in the right corner as below.

  • Now after clicking manage, it will get redirected to the vendor’s dashboard. And then go to “BROWSER” tab and then here we can execute the SQL query (select * from application_meta) as below:

  • Now the above query fetched the metadata which resides in the database. This is done by the code which we have written in application start up command i.e. inside the run method in java class.

Now we see that our application is running fine inside pivotal cloud foundry and it has a service instance name as MypostgreSQL through which app can interact with it inside the cloud environment.

Interview Questions on the Topics we covered:

These are the basic frequently asked interview questions in PCF from the topic which we covered in this article. Advance PCF questions I will mention in our upcoming PCF interview article about PCF Advance Concepts with security, scalability and High availability.

Note: Here the answers are not provided. Wil find all details in our upcoming PCF interview Question and Answer article

Ø What if we are not providing the buildpack in the yaml file?

Ø What are the steps to deploy a Spring Boot Application to PCF?

Ø How CF push operation work internally?

Ø What are the YAML file configuration properties required to deploy Spring Boot Application to PCF?

Ø How many ways can be possible to interact with PCF?

Ø What is the significance of “Services” in pivotal cloud Foundry?

Ø How to host a simple static file in PCF?

Ø Anatomy of Org, Spaces and Roles in PCF

Conclusion:

The application that we created in this article is very simple spring boot rest-based application. Finally, at the end of this chapter we have a working application inside pivotal cloud foundry that has a service instance as postgreSQL and it can interact with it inside the cloud environment.