Go back to Read chapters

Download Rating API and add likes to users content for hot topics and feeds

Download Content rating backend application interface and learn how to use it for your own innovative applications. Learn also how to secure an endpoint using Spring Security's basic authentication.


Great, now you have read the previous chapters you understand how rating systems work. So let's get straight forward and implement our own. The implementation uses same techniques as the previous chapters but for this application we add a basic security case with application users, roles and a default login page. Sounds complicated, well it is and it is not when you learn it. 

Programming likes

The main points in this chapter are:

  • How to implement user's content rating algorithm with different configurations that are used to configure ratings for users likes or votes.

  • Spring Security Basic Authentication with default users. This includes securing a Spring boot application with multiple predefined users but does not include user registration. Multiple users and registration will be described simply in the upcoming chapters.
These upcoming chapters are related to this chapter as well:
  • How to integrate a web application into Spring Boot application.
  • How to run the Spring Boot application inside a Raspberry PI as a distributed application. This will be described more in the upcoming chapters.
  • How to integrate a 3d world into a Spring Boot application This is a more interesting additional feature that will be described in the upcoming chapters.

Store users's likes and votes in a database

Let's look at how the Rating API is constructed. The approach we use in describing is to start from the point where the data is stored and handled, the database and the model for the data, then go up to the data access layer and after that to the service layer and finally to the REST application interface (API) layer.

Rating user's content in a feed

So how the user's ratings are modeled? First of all we need the information on the user that has rated the content. This is used to know what content the user already has rated and to prevent multiple ratings. The user can give only one rating to each content. One content can have multiple ratings from many users. And the total ratings points are calculated in a bufffered Integer in the content object.
The user is referenced with an user identification field in the Content class. In this microservice application we don't yet have created the actual User class to reference to so we store the user identification number. This could be lateron changed to OneToOne association in Hibernate.

public class Content extends BaseEntityAbstract {


private String ownerId;

The total points are calculated in the following attribute totalPoints.


private Long totalPoints;

Storing the user's ratings

The Rated class creates a connection between the user that has rated a specific Content. The source code comments are now added for documentation and clarity. Rated object has binding to Content and it has the users's Id reference and the points that the user has given.

public class Rated extends BaseEntityAbstract {


* The Content object that the user has rated



private Content content;


* User that rated the content


@Column(nullable = false)

private String userId;


* The points that the user gave as rating


@Column(nullable = false)

private Long points;

This is a simple structure to store the content ratings and to bind the ratings to users. 

Install the Rating API microservice

Download the Rating API source code, import it to your Eclipse Java IDE. Follow the instructions in previous chapters to install new version of the following.

Additional configuration for Maven settings.xml add the following plugin group to build docker image.



Create Rating API Database

Do the required steps to create a database as in the previous chapter http://weall.com/book/chapter/Download-Connecting-API After that update the database rights to the following tabes rated, content, content_hashtags, hashtag with the following SQL Grant sentences. 
CREATE DATABASE IF NOT EXISTS socialnetworkingpatterns CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
GRANT ALL PRIVILEGES ON socialnetworkingpatterns.content_hashtags TO '[USERNAME]'@'[LOCALHOST_IP]' IDENTIFIED BY '[PASSWORD]';

Run Rating API

Download the Rating application from the end of this chapter and run it either with Spring Boot

mvn clean package spring-boot:run

or with Docker

mvn clean package docker:build -Pdocker 

And start the image with Docker (fill the fields below)

docker run -e "SPRING_PROFILES_ACTIVE=docker" -e "SPRING_DATASOURCE_URL=jdbc:mysql://[DOCKER_DATABASE_IP]:[DOCKER_DATABASE_PORT]/socialnetworkingpatterns" -e "SPRING_DATASOURCE_USERNAME=[USERNAME]" -e "SPRING_DATASOURCE_PASSWORD=[PASSWORD]" -e "SPRING_JPA_HIBERNATE_DLL_AUTO=create" -e "SERVICE_RATING_PORT=5008" -p 5008:5008 --name=rating -t weallcom/rating

This is an Actual run example for testing

docker run -e "SPRING_PROFILES_ACTIVE=docker" -e "SPRING_DATASOURCE_URL=jdbc:mysql://" -e "SPRING_DATASOURCE_USERNAME=testuser" -e "SPRING_DATASOURCE_PASSWORD=testpass12345" -e "SPRING_JPA_HIBERNATE_DLL_AUTO=create" -e "SERVICE_RATING_PORT=5008" -p 5008:5008 --name=rating -t weallcom/rating

Notice to use the Hibernate auto database creation parameter accordingly


create = Create database

update = Update database with applying alter statements to tables, does not drop columns

validate = Validate the database tables

Other options are documented here Spring Boot Initialize Database using JPA

Login to Rating API

Open a browser and head on to the address http://localhost:5008

Or using Docker open a browser and head on to the address or http://[DOCKER_IP]:5008

Login with a username john and password john1

Testing the application with HAL Browser

The application uses HAL user interface for testing purposes. The application is not designed according to HAL specifications. It is used only for testing to send GET and POST test messages to the application. More about HAL specification here http://stateless.co/hal_specification.html

The application uses HAL Browser to send test content to the application. We user the HAL browser's feature to send a POST message to a different test URL, not the one that the HAL browser in default gives.

Create a new content in the HAL browser screen click on Links / profile / NON-GET button. Write the following test url to make a POST request
Click on Make Request.
Click on button Links / profile / NON-GET to add a new POST request and replace your own address line to the Action field as
Verify that the rating is calculated correctly by writing to the Explorer field the following url

Logout by going to address http://localhost:5008/logout

Login with another username jill and password jill1

As Jill user rate John's message with
And see the accumulated points with, totalPoints should now be 2

How to program a rating or voting algorithm 

From now on we look at the Rating API source code and what it has eaten

The rating algorithm itself is simple:

  1. First find from Rated if the user has already rated the content
  2. If not then rate the content by saving it as Rated and add the accumulated points to the Content
  3. If user has rated the content don't rate it twice
To be noted that the rating algorithm is easy for this scenario, when the user only adds ratings. It gets more complicated when the user removes the ratings and thus the total accumulated points have to be changed. There is a risk that is error situation the accumulated points differ from the total Rated points. This can occur on error situation when the Rated database row has been saved but the total points have not yet been saved and in between the actions the database connection will be terminated. That's why the algorithm uses the @Transactional and @Modifying annotation attributes. 

Spring Data HAL Browser

There is a Spring Data HAL Browser for testing purposes in the package. Make sure to remove the dependency from POM.xml when you install the package. The HAL browser generates the user interface for testing the interfaces and REST data.





How to get a stream of hot topics

The application uses a filter to sort the content based on two sorting filters.

Hot topics means that the content is ordered by the more popular content by rating it with the total rating points. A more sophisticated algorithm can take also account the view times of content, comments or messages of content and an analyzation of the content structure or message and use these for sorting. So simply the content algorithms are just a way to sort the content based on pre-calculated variables. 

Pre-calculated means that the variables perform faster when they are pre-calculated. When doing a search you don't have to each time calculate the sums of the ratings for each content.
The Rating API uses Java 8 and to be noted with these changes: 
  • java.util.Date are changed to java.time.LocalDateTime Rating API's Hibernate version automatically has built in conversion to map LocalDateTime to database.

Spring Security login with multiple users

Spring Security is introduced in the Rating API to secure the REST interfaces to allow only users with USER roles to make queries to interfaces. 
As a bonus there is an additional configuration to allow multiple static users that are loaded from application.properties file. The configuration is done with MultipleUserConfigurer configuration in the RatingApplication. 
This means that you may statically enter the user names and their passwords in the application.yml file. Note that in Spring Boot Basic authentication the passwords are stored in clear text so they should not be generated for each user. Multiple users cannot be dynamically added to the configuration, the current service must be restarted to load the changed configuration. 
Note that in newer Spring Boot versions thre is a possibility to use the PasswordEncoder to use for example BCRYPT to verify the password.

Download Rating API Docker microservice

Below is the Download section for the Rating API Docker microservice. Please login to access the Download section.

Rating API is now documented by public request, thanks to all feedback from Quora.

Rating API Javadoc rating-0.1.0-RELEASE 


What new ideas or thoughts this chapter gave you?