fabiochiu/medium-articles huggingface dataset:
Keycloak & Spring Boot Disable CORS
Tags: Keycloak, Spring Boot, Cors, Spring

It took me a while to achieve this, I think someone will need it

@KeycloakConfiguration

class SecurityConfig extends KeycloakWebSecurityConfigurerAdapter { @Bean

public FilterRegistrationBean corsFilter() {

UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();

CorsConfiguration config = new CorsConfiguration().applyPermitDefaultValues();

source.registerCorsConfiguration("/**", config);

FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));

bean.setOrder(Ordered.HIGHEST_PRECEDENCE);

return bean;

} @Override

protected void configure(HttpSecurity http) throws Exception {

super.configure(http);



http.addFilter(corsFilter().getFilter())...

.anyRequest().authenticated() } }
Load spring boot app properties from database - before application start
By: Ankit Wasankar
Tags: Application Properties, Spring Boot, Database, Configuration File, Spring

Load properties from database before application start — Spring boot

Why do we even need to do that?

Sometimes we need to load the properties from database because they are flexible to use .

. Sometimes we need to load database properties because we have different database property values in TEST and PROD .

. My reason to load the properties from database because our application has UI for changing properties stored in the database and depending upon the change in properties our applications should behave after restart. For ex: If CORS is enabled through UI, then CORS configuration should be conditionally picked while restart depending upon the property value.

How to do it in Spring boot?

For those who need load properties from database before application starts, and make those props accessible by @Value anywhere in your project, just add this processor.

Eve if you copy paste the code with below database table, the code will work as is, we will go step by step through the code later.

Create database table with below columns

The create new class with below code

Understanding the code

Spring boot will call initialize() method automatically while stating the application but before loading the configuration classes but after loading the application properties.

method automatically while stating the application but before loading the configuration classes but after loading the application properties. There we checked if we have already loaded the properties or not .

. getPropertyMapFromDatabase() this method will actually connect to database and then fetch values and put into Spring boot properties.

this method will actually connect to database and then fetch values and put into Spring boot properties. There is one extra method ViperUtils.isNotBlank() to check blank which is as follows:

public static boolean isNotBlank(Object obj) {

if (obj == null) return false;

if (obj instanceof String) {

return ((String) obj).length() > 0;

}

return true;

}

Why I used old fashioned connection & Prepared Statement?

Data source is not yet created, when the flow comes to this class. Spring boot is yet to load the configurations. So we can manually create the data-source. But then why to hassle with creating data-source when we just need just single connection to database to load the properties. If you create the data-source here you need to keep in mind that while loading configuration classes Spring should not create again.

And again while shutting down the application, Spring boot must close the data-source, even if you created from this class. Otherwise there will be stale connections to database.

So, after weighing the advantages and ease I think it’s better to make a single connection to database to load the properties and then close the connection. And then let Spring boot create data-source from configurations or auto-configurations. Spring will auto manage those connections.

Any questions or queries, let me know in comments ?
Spring Web Security for HTTP Request.
By: Inzamamul Haque
Tags: Spring Boot, Http Client, Json, Http Request, Spring

Passionate for writing & Coding, Self Motivated Software Developer. Skilled in Java, Ionic framework, Spring boot, Grails framework, Angular.
Problems I faced(Part-1)-Authentication as Zuul filter or Servlet filter?
By: Samiul Mushfik
Tags: Spring Boot, Authentication, Netflix Zuul, Servlet

Recently, in one of projects I have been working on needed to introduce manual authentication mechanism — did not use Spring Security, rather manually handled JWT token validation and so on. For this purpose, what I had to do is to intercept requests to validate their authenticity before serving them.

As I was already using zuul for routing requests, I introduced a zuul pre-filter which basically intercepted requests to authenticate them before forwarding them inwards. It worked well as expected. But the problem arose when I sent requests using my own component’s APIs rather than other components’. As zuul was not routing these requests, these were not intercepted by my previously written zuul pre-filter.

What I came to know later that in Spring Boot 2, zuul servlet responsible for routing is placed after dispatcher servlet in the whole request path flow. So basically dispatcher servlet is the only front door that lets every request, one needed to route to another component or one in the same component as zuul is configured, in.

Typical request flow(Simplified)

So I relocated the previously written filter logic responsible for authentication before dispatcher servlet and voila!. It worked. However, this new filter is no more zuul filter rather servlet filter. How interesting is that!
The whole design of bean validation is built around ugly practice of “business level exceptions”.
By: Sergiy Yevtushenko
Tags: Java, Spring Boot, Bad Practices, Spring

The whole design of bean validation is built around ugly practice of “business level exceptions”. Spring always been promoting bad practices, including this one.
Amazon MQ (RabbitMQ) and Spring Boot AMQP Connection 12.2020
By: Archie Sheran
Tags: Spring Boot, Rabbitmq, Amazon Mq

Had issues finding the autoconfig parameters for Amazon MQ that work with spring, most examples where outdated, I managed to connect eventually. Follow the instructions from Amazon to setup a Rabbit MQ Broker.

Your endpoint should be publicly accesible and you should get an endpoint adress starting with amqps

On the spring side add the dependency for amqp

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-amqp</artifactId>

</dependency>

on your application.properties file configure the connection using the url from the amazon console as follows

spring.rabbitmq.addresses=amqps://your-url:5671

spring.rabbitmq.username=dmeo

spring.rabbitmq.password=demo

You can now follow the examples you find online to send messages to the broker, this one worked well for me

https://github.com/thombergs/code-examples/tree/master/spring-boot/request-response
Explore Spring MVC Architecture. Nowadays, developers tend to move…
By: Nil Madhab
Tags: Java, Spring Boot, Backend Development, Mvc Frameworks, Web Development

Photo by Safar Safarov on Unsplash

Nowadays, developers tend to move towards frameworks than using the actual Language itself for development. The reason is their simplicity as well as their power of development.

Considering Spring, it is totally a monster of frameworks! Spring has many advantages; Spring provides a lightweight container that can be activated without using a web server or application server software. It gives good support for IoC (Inversion of Control) and Dependency Injection results in loose coupling. With that, the interaction with the Database becomes a piece of cake!

In this tutorial, we are gonna develop a site in our local server that supports user registration and login using spring boot. We are going to follow MVC (Model — View — Controller) architecture in this tutorial.
Basic Introduction to Spring WebFlux
By: Christopher Anatalio
Tags: Java, Spring Framework, Spring Webflux, Reactive Programming, Spring Boot

Annotated Spring WebFlux RestController

Here is an example of an annotated Spring WebFlux Controller:

Spring WebFlux Controller Example

@RestController

@RequestMapping("api /v1/room/reservation/ ")

public class ReservationResource { @GetMapping(path = "/{roomId}")

public Mono<Reservation> getReservationById(@PathVariable Mono< String> roomId) { return //Call your service layer here

}

}

View the source code for this Controller in the context of a Full Reactive application with Spring WebFlux and Angular

As you can see this code is very similar to Spring MVC with the exception of the return type being a Reactive Publisher, in this case a Mono that emits a Reservation object(A DTO from this sample project).

Mono: a Reactive Publisher that emits 1 or zero elements than terminates.

In other words, a Mono is like an async, promise or a future that will emit an element.

From the Spring JavaDocs for the Mono type:

A Reactive Streams Publisher with basic rx operators that emits at most one item via the onNext signal then terminates with an onComplete signal (successful Mono, with or without value), or only emits a single onError signal (failed Mono).

Mono in Action

Spring Reactive Publisher Mono in Action

Subscribers to the Mono will receive a single emitted element(Or an error signal) and then a completion signal.

Using a Spring Data Reactive Repository

Now that you have a Reactive Controller, you will then want to hook into a Service layer that leverages a Spring Data Reactive Repository.

Spring Reactive Repository Example

public interface ReactiveReservationRepository

extends ReactiveCrudRepository<Reservation, String> {



Mono<Reservation> findById(Mono<String> roomId);

}

Checkout this article for more details on how to configure Spring Reactive Data: https://spring.io/blog/2016/11/28/going-reactive-with-spring-data

Calling a Reactive Repository from a WebFlux Controller

@RestController

@RequestMapping("api /v1/room/reservation/ ")

public class ReservationResource { ... @GetMapping(path = "/{roomId}")

public Mono<Reservation> getReservationById(@PathVariable Mono<String> roomId) { // It is implied this @Bean is @Autowired into this class

return reactiveReservationRepository.findById(roomId);

} ... }

If you use a service layer, be sure to make the return type of your service methods a Reactive Publisher like Mono or Flux.

Sample Project

Check out this Github repo for a full example of a Reactive Application.

Full-stack Spring Boot and Angular App
Hot vs Cold Reactive Streams
By: Kathiriya Niket
Tags: Reactor Project, Reactive Programming, Streaming, Spring Boot, Flux

Let’s suppose there is a producer that produces integers 1 to 10.

Now, a subscriber will subscribe and request for data.

The publisher starts sending data through onNext() event.

PubSub example for Hot/Cold streams

When the publisher has sent 3 onNext() events, another subscriber (subscriber-2) will subscribe and request for data. This can lead to 2 possible scenarios.

Case 1:- The publisher sends data to the subscriber — 2 from the beginning (from 1) and keeps sending the data in continuing sequence to the running subscriber. This type of publisher is called Cold Publisher.

Cold Publisher

Cold Publisher: “For every subscriber, the items start from the beginning.”

Case 2:- The publisher sends the same data to subscriber — 2 that it is currently giving to the running subscriber. This type of publisher is called Hot Publisher.

Hot Publisher
Spring Boot + Kubernetes — Scalability with Horizontal Pod Autoscaler (HPA)
By: Andrea Scanzani
Tags: Java, Spring Boot, Kubernetes, Docker, Software Development

Spring Boot Microservice

First of all, let’s create our project with Maven, below we report the pom.xml useful to satisfy Spring Boot dependencies:

pom.xml

Our pom.xml is minimal as we are going to use only two Spring Boot dependencies:

spring-boot-starter-web → For creating a REST Service spring-boot-starter-actuator → To expose our Health, Liveness and Readiness endpoints

To configure the actuator and tell it that we also want to expose the Probe Services for Kubernetes, we create the ‘application.properties’ file and insert the following line:

management.health.probes.enabled=true

Let’s proceed with the writing of a minimal REST Service, with only one GET (HTTP Method) Endpoint:

Java Code

In the controller we have added a logic to increase the CPU usage (to simulate the computational logic of a real application).

Now our Microservice is ready and we can run it from the command line:

mvn clean spring-boot:run

The Spring Boot Application now exposes the service:

http://localhost:8080/sayHello → REST service with application “logic”

http://localhost:8080/actuator → REST Service which lists all REST Services available through Actuator

Our application is now ready to be Conteinerized, so we’re going to create our Docker image. To create it we need to have the Dockerfile to compose the image Layers.

This is our Dockerfile:

Dockerfile

The FROM instruction indicates which image we are going to use as Runtime of our Spring Boot App, then with ARG and COPY we go to insert our created JAR and the ENTRYPOINT instruction indicates how the container should start the application.

Note: We are using the balenalib/armv7hf-alpine-openjdk:8 image as our image will run on the Raspberry Pi, as we have already ready the Docker + Kubernetes (K3s) environment executed in this Post. If your image is to run on an architecture other than the ARMv7 32Bit (Raspberry Pi) you need to use another image in the FROM instruction.

Now everything is ready to build our Docker image:

mvn clean package docker build -t spring-boot/hello-app .

At the end of the process we find our image in the local Docker registry:

docker image ls

And we will have the following output:
Dockerizing a SpringBoot Application (Kotlin and Gradle) and Deploying it to your Local Kubernetes Cluster
By: Vedant Tiwari
Tags: Spring Boot, Kubernetes, Gradle, Kotlin, Docker

Let’s look at what is docker and why do we need it.

An application works in developer’s laptop but not in testing or production.

This is due to difference in computing environments.

Developing an application requires starting several of microservices in one machine. So if you are starting five of those services you require five Virtual Machine’s on that host machine.

Using VM’s leads to wastage of resources.

Docker containers are light weight alternatives of VM’s. In docker container we don’t have to pre-allocate any RAM or disk space, they take RAM or disk space according to requirement and provide a consistent computing environment throughout the whole SDLC(Software Development Life Cycle).

Docker in a Nutshell: -

Docker file builds a Docker image and that image contains all the project’s source code. You can run that image to create as many Docker containers as you want. Then this image be can uploaded on Docker hub, from docker hub anyone can pull the image and build a container.

Let’s take a look at Kubernetes now: -

Kubernetes is all about managing containers on virtual machines or nodes. The nodes in the containers they run are grouped together as a cluster , and each container has endpoints, DNS, storage and scalability.

In short Kubernetes is a Container Management Tool!.

Kubernetes is an opensource container management tool which automates container deployment, container (de)scaling and container load balancing.

So Docker is a containerization platform and Kubernetes is a container management tool.

Please note: Kubernetes is NOT for application with a simple architecture.
Java 與 Spring 結合的多執行緒處理
By: Bruce Hsu
Tags: Java, Asynchronous, Thread Pool, Spring Boot, Spring

I'm a Java engineer, eager to learn new skills, technique and willing to take challenges.
JUnit: testing API with WebTestClient
By: Kathiriya Niket
Tags: Reactor Project, Reactive Programming, Spring Boot, Flux, Junit

For the sake of getting straight to the point, we will assume followings, so that we can look directly into testing.

We have a RestController with two get mappings. ‘/flux’ returns Flux<Integer> in default media type — application/json. ‘/fluxStream’ returns Flux<Long> in — application/stream+json OR application/x-ndjson. ‘/flux’ is finite and will return (1,2,3,4). /fluxStream’ is infinite and will return (1,2,3,4,5….).

Let’s look at few of the ways to test an API using WebTestClient.

@RunWith(SpringRunner.class)

@WebFluxTest

public class testDemo{

@Autowired

WebTestClient webTestClient; @Test

public void flux_approach1(){

Flux<Integer> integerFlux = webTestClient.get().uri("/flux")

.accept("application/json")

.exchange()

.expectStatus().isOk()

.returnResult(Integer.class)

.getResponseBody(); StepVerifier.create(integerFlux)

.expectSubscription()

.expectNext(1,2,3,4)

.verifyComplete();

} @Test

public void flux_approach2(){

Flux<Integer> integerFlux = webTestClient.get().uri("/flux")

.accept("application/json")

.exchange()

.expectStatus().isOk()

.expectHeader().contentType("application/json")

.expectBodyList(Integer.class)

.hasSize(4);

} @Test

public void flux_approach3(){

List<Integer> expectedIntegerList = Arrays.asList(1,2,3,4); EntityExchangeResult<List<Integer>> eeResult = webTestClient.get().uri("/flux")

.accept("application/json")

.exchange()

.expectStatus().isOk()

.expectHeader().contentType("application/json")

.expectBodyList(Integer.class)

.returnResult(); assertEquals(expectedIntegerList,eeResult.getResponseBody());

} @Test

public void flux_approach4(){

List<Integer> expectedIntegerList = Arrays.asList(1,2,3,4); webTestClient.get().uri("/flux")

.accept("application/json")

.exchange()

.expectStatus().isOk()

.expectHeader().contentType("application/json")

.expectBodyList(Integer.class)

.consumeWith((eeResult) -> {

assertEquals(expectedIntegerList,eeResult.getResponseBody());

});

}

}

@WebFluxTest will only instantiate RestControllers. If we are using any Components, Services or Repositories, then use @SpringBootTest with @AutoConfigureWebTestClient.

What to do in case of infinite flux?

@Test

public void fluxStream(){

Flux<Long> longStreamFlux = webTestClient.get().uri("/fluxStream")

.accept("application/stream+json")

.exchange()

.expectStatus().isOk()

.returnResult(Long.class)

.getResponseBody(); StepVerifier.create(integerFlux)

.expectSubscription()

.expectNext(1L,2L,3L)

.thenCancel()

.verify();

}
Spring Boot With H2 Database
By: Tayfun Çeli̇k
Tags: Spring Boot, H2, H2 Db, Spring Boot 2, Spring Boot Wiht H2

begin with the h2 and spring-boot-starter-data-jpa dependencies:

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-data-jpa</artifactId>

</dependency> <dependency>

<groupId>com.h2database</groupId>

<artifactId>h2</artifactId>

<scope>runtime</scope>

</dependency>

Database Configuration

By default, Spring Boot configures the application to connect to an in-memory store with the username sa and an empty password.

However, we can change those parameters by adding the following properties to the application.properties file:

Default password is empty but when you write any “ password “ you just assign new passoword

spring.datasource.url=jdbc:h2:mem:testdb

spring.datasource.driverClassName=org.h2.Driver

spring.datasource.username=sa

spring.datasource.password=password

spring.jpa.database-platform=org.hibernate.dialect.H2Dialect

we can change the location of data store FILE-BASED instead of IN MEMORY

spring.datasource.url=jdbc:h2:file:/data/demo

Accessing the H2 Console

If we don’t enable it we can not access, we need to add the following property to application.properties:

spring.h2.console.enabled=true

Check the link http://localhost:8080/h2-console

If you will change the jdbc url: as jdbc:h2:file:/data/demo

We will get this error

A file path that is implicitly relative to the current working directory is not allowed in the database URL “jdbc:h2:file:/data/demo”. Use an absolute path, ~/name, ./name, or the baseDir setting instead.

So we just create a file directory jdbc:h2:file:D:/data

If we want to change the url just add another configuration to application.properties

spring.h2.console.path=/h2-console

ref: https://www.baeldung.com/spring-boot-h2-database
Hibernate Reactive with Spring Boot 2
By: Diego Pacheco
Tags: Java, Hibernate, Spring Boot, Reactive, Hibernate Reactive

Reactive programming is not a new thing. Thanks to reactivex and rx-java it’s a reality for almost 10 years. There are other implementations like Project Reactor and even Vert.x. However, for Databases, we are still not there. Some databases have better support than others like Cassandra and Redis have decent support in drivers but JDBC and JPA are not quite there yet. Hibernate just went reactive. There is a hibernate-reactive project now(still beta 1.0) but looking promising. So today I want to share some simple POC I made to make Hibernate Reactive work with Spring Boot 2.x using webflux: using Netty of course. So I made a video going throught the code and explaining how it works. I personally worked with all sorts of persistence on the last +17 years on technology but not an ORM fan nowadays. However I always appreciate performance and better APIs, so I think this is promising even if is for legacy application modernization.

The Video

The code

Cheers,

Diego Pacheco
Helping Santa Claus with a Spring Boot microservice
By: Thomas Surmann
Tags: Spring Boot, Microservices, Rest Api, Hibernate

With Bootify you can initialize a Spring Boot application with your own database schema and REST API. In this article we want to create a small example backend that allows Santa Claus to manage the delivery of his presents. How else is he supposed to keep track of the millions of children?

Santa Claus tracking the visits on his iPhone

First steps and database schema

We begin on Bootify.io by clicking on Start Project. The project gets its own URL, which we may bookmark for future reference.

Now we are in the general settings where we want to keep Gradle as a build tool. Santa’s datacenter is working with MySQL and Java8 , so we make this two choices. Lombok saves us a lot of Getters and Setters, so we activate this option too.

Next we can create our schema in the tab “Entities”. The finished schema is shown later on, but at first we start with the table “Child”. Besides the primary key, this table has a “name” ( unique String with 1000 characters, so that every child can be identified), a “dateOfBirth” (type LocalDate ) and “didBehave” (type Boolean ) – not every child gets a gift.

Creating our first table in Bootify

After that we come to the second table “Present”. There is only a limited number of gifts that are actually wishable, divided by age groups. Therefore we’re including the custom fields minAge, maxAge (type Integer ) and description (type Text ).

Second table for the presents produced at Santa’s workshop

Santa Claus is going to track the visits via his iPhone, for which we add the third table “PresentDelivery”. Here there is only the extra field sungSong ( String ), but after creating the table we insert two more relations describing our foreign keys.

Creating our foreign keys

PresentDelivery refers to a Child in the ratio N:1. The name “child” is sufficient for us here and we want to mark the relation as required. In the same way we create the relation to the Present table. Our scheme is now complete and we can examine the result in the UML preview.

UML Preview of our final schema in Bootify

Code review and download

This means that we are already finished with the initial version of our microservice! Using “Explore” we can look at the generated code and see not only the JPA / Hibernate entities, but also the services and rest controllers that provide basic CRUD functionality.

Exploring the generated code of our new microservice

Honestly, one could have made the database schema a bit more precise, so that Santa Claus can manage the behaviours and presents separately for each year. If you would like to improve that, get a copy of the project on the following link and extend it as you like: https://bootify.io/helping-santa-claus

The elves are still working on the iPhone app — hopefully everything will be ready in time. Be good and have a nice christmas time!

This article has been published as part of this years Java Advent.
Microservice
By: Narayana Basetty
Tags: Microservices, Spring Boot, Jax Ws, Swagger, Oauth2

What is microservice?

An application decomposed into collection of loosely coupled services.

Microservice is a architectural style - It’s a variant of the service-oriented architecture (SOA) structural style.

Advantages of microservice over monolithic.



Services are fine-grained.

The protocols are lightweight.

Highly maintainable and testable.

Independently deployable.

Organized around business capabilities.

Who are all supported microservice implementation?

Spring Software Platform supports Microservice by using Spring Boot framework.(https://spring.io/)

Spark (http://sparkjava.com/)

JAX-RS (https://docs.oracle.com/javaee/6/tutorial/doc/giepu.html)

etc.

Spring or Spark, etc. supports REST API services over HTTP transport.

HTTP operations like GET, POST, PUT, DELETE, etc.

Swagger is a OpenAPI standards product supports all authentication and authorization for an API.

Swagger provides beautiful UI to see REST API, method allowed, parameter details etc.
Write Simple Spring Boot App for get currency rate
By: Yegor Voronyansky
Tags: Java, Fintech, Spring Boot, Software, Software Development

Within the framework of this article, we will develop an application for receiving exchange rates from the central bank of Russia. The main technologies we will be using will be Java, Spring Boot, Docker, Vue

1. Let’s start by choosing the required method in the API of the central bank, which is allowed to get the current rates

2. Next, let’s add WSDL processing to the application so that we don’t have to do it by hand

3. We use Spring WebServices so that our application can skillfully request data from the API

4. Add Swagger to the application

5. Add some Vue frontend

6. Connect Docker

The first thing we need is, of course, to create an application — this can be done using the Spring Initializr or through IntelliJ IDEA.

Creation of the project

The API method we’ll be using from the central bank is called GetCursOnDateXML. Below you can see its description.

Description of this method

In order not to describe the structure of requests and responses from the API ourselves, we will use plugins that will help turn WSDL into POJO. Listing pom.xml

Let’s check that the plugin really works and the classes we need are created — screen.

Generate POJO from WSDL

Now let’s add a web service that will be responsible for executing the request and response. Listing of creating a web service.

Great, the MVP of the application is almost complete. Now let’s add REST controllers so that we can send the received data from the third-party API outside. We will have one controller and two entry points — receiving all currencies, and receiving a specific currency at the moment.

Entrypoints of application

Let’s add Swagger to our application so that all consumers of our API know the contracts for interacting with the system.In order to add Swagger, you need to add one dependency and write the configuration code. Let’s check that Swagger actually works. However, we need a complete UI. To do this, let’s add another dependency and make sure that everything worked correctly.

Add Swagger and Swagger UI

We have an API, but at the moment we can display currencies only in JSON form. Let’s add a little frontend in Vue.

Front end part

Now, we should add service instance for interact with our backend.

We’ll also add Docker for our convenience. Our Dockerfile will look like this

Simple Dockerfile

Let’s run our application

Our app is working!

And last, but not least let’s write unit test — for check that our app works correctly

First test

Second test

That’s all for me, I hope you liked the article Write comments and subscribe
Make Your Microservices Bulletproof With Netflix Hystrix
By: Rafael Martins
Tags: Programming, Netflix, Java, Architectural Design, Spring Boot

# What is a circuit breaker (CB)?

Just by analyzing the simple Wikipedia definition:

A circuit breaker is an automatically operated electrical switch designed to protect an electrical circuit from damage caused by excess current from an overload or short circuit. Its basic function is to interrupt current flow after a fault is detected.

Mapping the concept to our context, when a remote service is called, this call will be monitored by the CB. If the call takes too long, the CB will catch the call and kill it. With this monitorization, the CB will be able to count the number of calls failed and then, fail fast and proceed accordingly.

You may wonder, why fail fast and not just wait? Let’s answer it with a simple example.

Imagine the following, we have two applications A and B. The A fetches some information from its database, and then, it requests a resource from application B (a receipt). The requested service (application B), external to application A, fetches data from its internal database, and then it requests an external service to generate a receipt based on it. This external service (application B) will then generate, save and return one file.

Let’s see the following diagram flow:

Over time, a new release of the recept application comes out, and for some reason, a new bug is introduced, and it starts to perform extremely slowly.

The engineer who wrote Application B never anticipated this type of behavior, so his code was actually calling the receipt service and then saving the correspondent receipt into its own DB, both operations in the same transaction. Not only does this cause the thread pool for requests to the receipt service to start backing up, but the number of database connections in the service container’s connection pool becomes exhausted due to these connections that are being held open because the call out to the receipt service never ends.

Therefore, application A, who started this workflow, starts running out of resources due to the call of service B that’s kept on hold.

And with this, you may wonder, why don’t we just fail fast? And now you realize you answered the question above.

To solve such a problem we include the CB in the following diagram:

With the CB inclusion, when the receipt application starts performing poorly, the circuit breaker for that specific call will trip and fail fast without eating up the thread. Only endpoints that interacted with that specific service will have been affected, so all the other functionalities will be working normally as nothing happened.

Such a small change would be enough to protect applications A and B from completely crashing.
Criteria Queries and JPA Metamodel with Spring Boot and Kotlin
By: Antonello Zanini
Tags: Hibernate, Spring Boot, Kotlin, Software Engineering, Software Development

Canonical Metamodel

The metamodel is a set of objects that describe your domain model.

[…]

This metamodel is important in 2 ways. First, it allows providers and frameworks a generic way to deal with an application’s domain model. […]

Second, from an application writer’s perspective, it allows very fluent expression of completely type-safe criteria queries. — Hibernate Community Documentation

The structure of the metamodel classes is described in the JPA 2 (JSR 317) specification. If you are interested in understanding in detail how metamodel classes are defined, I recommend reading this documentation page first. Otherwise, feel free to skip to the next chapter.

Configuring a Metamodel Generation Tool

To generate the metamodel classes, we will use hibernate-jpamodelgen , the metamodel generator tool provided by JBoss.

First of all, we need to add the hibernate-jpamodelgen dependency to our build.gradle.kts file, as well the kapt plugin.

plugins {

kotlin("kapt") version "1.3.72"

} dependencies {

implementation ("org.hibernate:hibernate-jpamodelgen:5.4.12.Final")



kapt("org.hibernate:hibernate-jpamodelgen:5.4.12.Final")

}

kapt is the Kotlin Annotation Processing Tool and it is required by hibernate-jpamodelgen to automatically generate the metamodel classes during build-time.

JPA Metamodel Classes

To show what a metamodel class looks like, we need an entity class. Since defining JPA entities in Koltin can be tricky, I recommend reading this article first.

Let’s assume we have already defined the Author entity class as follows:

By default, the corresponding metamodel class will be placed by kapt in build/generated/source/kapt/ followed by the same package as the corresponding entity class.

The metamodel class will be automatically generated during build-time and will have the same name as the entity with an added “_” at the end. So, the metamodel class generated for the Author class will be Author_ and look like this:

As you can tell, the generate metamodel class is a Java class. This is not a problem since Kotlin is fully interoperable with Java.

JPA Metamodel In Action

Since the Criteria API provides overloaded methods that accept String references as well as Attribute interface implementations, we can use the generated metamodel classes in the same way we would use the String references to attributes. Let’s write the criteria query that will fetch all Authors named “John”.

This is what the criteria query using Author_ looks like:

And this is what it looks like without using the metamodel class:
Create and deploy Java Spring Boot application to Heroku cloud platform
By: Madhavendra Dutt
Tags: Java, Spring Boot, Deployment, Heroku

Start a new Spring Boot project

Either use Spring Boot CLI or go to https://start.spring.io/ to create a “web” project. In this step, I prefer the second option. In the “Dependencies” dialog search for and add the “Web” and “MySQL” dependency as shown in the screenshot. Hit the “Generate” button, download the zip, and unpack it into a folder on your computer.

Initialize Spring Boot Project

Open this project in Eclipse or IDE of your choice. I am using Eclipse. Import the above-downloaded project from File > Import, it will install all the dependencies and within a few minutes, you are ready to go.

Import the downloaded project

Create a package named “controller” by right-clicking src/main/java > New > Package

Create a package named controller

Then create a controller class “SpringQuestionController” by right-clicking controller package > New > Class and put request mapping for “/” and “/index”.

Here “/index” will return a view so the next step is to create an HTML file named index in src/main/resources/templates and put some content to display in the file.

Then add the dependency to parse HTML. Spring Boot provides auto-configuration for Thymeleaf by adding the spring-boot-starter-thymeleaf dependency.

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-thymeleaf</artifactId>

</dependency>

Now run the application and navigate to any one of the two mapped path http://127.0.0.1:8080 or http://127.0.0.1:8080/index
Java Hot code replace ( HotswapAgent + DCEVM )
By: Ashwin Sreekumar
Tags: Java, Debugging, Spring Boot, Hot Swap

Zdravo fellow java developers! Lets save some time :)

One of the most irritating aspect of coding in large java project is redeploying code. For some projects it might take upto 5 mins (maybe more)! And this has to be done for every small change and this is time consuming. With DCEVEM and Hotswap agent we can dynamically hot replace the code instantly.

To set it up we need to install DCEVM into our JRE.

Download the DCEVM binary from http://dcevm.github.io/ run: sudo java -jar installer.jar. Click on add installation directory and select your java home folder

4. Click on install DCEVM as altjvm.

Now we need to install hotswap agent in IntelIj.

5. Add the hotswap plugin in intellij and keep the options as shown below.

6. Now Download hotswap agent jar from here.

7. mvn spring-boot:run -DskipTests -Drun.jvmArguments="-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address= 5005 -XXaltjvm=dcevm -javaagent:/path/to/hotswap-agent.jar"

8. To hotswap the code, make sure you have a remote debug connection from intellij and then press cmd + shft + F9 (compile).

9. Done !!!!!

PS: Not all types of changes can be hot replaced. http://hotswapagent.org/
Publish Java Spring Boot App in Cloud
By: Nil Madhab
Tags: Deployment, Spring Boot, Digitalocean, Cloud Services, DevOps

Setting up the VPS

To start off with, head on over to Digital Ocean and click on either “Sign In” or “Sign Up” (or the VPS provider of your choice).

Once you have an account you can go to your dashboard. Click on “Create” and then “Droplets”.

For our droplet, we are going to choose Ubuntu 20.04 (LTS) as our image of choice. For the uninitiated, this is a very easy-to-use distribution of Linux based on Debian, it’s also the one I use on a personal basis.

We are just going to choose the basic plan of $5/mo since there is no reason to get anything more expensive. We are not going to add any block storage. Feel free to choose any region you want, personally, I am just going to choose Frankfurt. We are not going to get any additional options.

Our authentication option will be via password, so enter a root password of your choice. When you reach the “Choose a hostname” point you should give it a name of your choice since this will be how you recognize your droplet, and I don’t know about you but if I had a list of droplets all with a name similar to “ubuntu-s-1vcpu-1gb-fra1–01” I would never be able to tell them apart, so I am just gonna change the hostname of mine to something more recognizable, “Spring-Boot-Cloud”. I am also not going to enable backups since I am doubtful that this droplet will last very long. Click on “Create Droplet”.

Your droplet will get booted up as a normal computer would. Once it has finished you will be able to interface with it through the website or through your terminal.

When you open the console for the first time it will ask for your “Login”, you just type “root”. Next, it will ask for your password, this is the password you had to enter when you initially created your droplet. After that you will see something like this:
Jib: do we really need yet another container builder?
By: Rens Verhage
Tags: Java, Spring Boot, Containers, Jib, Docker

Photo by Paul Teysen on Unsplash

In a previous article, I wrote about how easy it is to build Docker images using Spring Boot 2.3. Recently, I learned about Jib, Google’s take on building container images for Java applications.

One might wonder if we really need yet another container image builder. In my opinion, Jib has some nice features that make it stand out from the crowd.

It’s easy

Not unique to Jib, but worth mentioning anyway: Jib is really easy to use. Just add the jib-plugin to your Maven pom:

<plugin>

<groupId>com.google.cloud.tools</groupId>

<artifactId>jib-maven-plugin</artifactId>

<version>2.7.0</version>

<configuration>

<to>

<image>${project.artifactId}:${project.version}</image>

</to>

</configuration>

</plugin>

This enables us to build an image and push it to the local registry using:

mvn jib:buildDocker

It’s that simple. By the way, I’m a Maven guy, so you Gradle girls and guys out there will have to come up with your own version 😉

It’s fast!

And by fast, I mean it’s really fast! With a clear cache, it took my about 9 seconds to build an image for a small Spring Boot application.

We can largely contribute this to the distroless base images used by Jib. These images only contain the packaged application and its runtime dependencies.

I wrote a simple Spring Boot HTTP echoserver and compared image sizes. Jib gave me a 214MB image, which is less than Spring Boot’s 276MB and way less than the whopping 395MB Docker produced using Alpine as a base image.

It’s secure

Because distroless images only contain an application and its runtime dependencies, their attack surface is minimal. Therefore, distroless images are considered to be more secure.

Of course, container security is not only defined by the contents of its image, but Jib sure gives us a head start.

It doesn’t need a Docker daemon

To me, this is definitely Jib’s best feature. Jib takes care of the entire building process and doesn’t need a running Docker daemon to do so.

This removes Docker as a dependency from our build environment.

Build pipelines will be more secure, since there is no need for exposing the host’s Docker daemon socket to our build containers.
Spring Boot web application for beginners.
By: Mohammed Shehzad
Tags: Spring Boot, Begginer, Web Development

Spring Boot is one of the widely used backend frameworks for developing web applications. It also helps the developer to build an application in a quick and simple way.

And this post will help you to start with setting up a spring boot application and run it in 5 easy steps

Although there are many ways to create a Spring Boot application, we will be using “Spring Initializr”.

Step 1: Go to https://start.spring.io/. Select Maven as Project, Java as language, and latest spring boot version.

To create a web application using Spring Boot, we need to add Web dependency to our project in the “Dependencies” section.

Spring Web dependency

Step 2: Select Project metadata, Packaging, and Java version. Use the “Generate” button to save/download the project. And extract the project to a folder.

Project Metadata

Step 3: Import maven project in IDE (I am using Eclipse IDE) as follows

File → Import → Maven → Existing Maven Projects (Click Next)

In Root Directory, browse to your project i.e. (example-application) and click “Finish”

import maven project in eclipse

Step 4: Create “TestController.java” as follows.

TestController.java code snippet

Step 5: Run “ExampleApplication.java” as a Java application. Go to browser and type “http://localhost:8080/test/hello-world”

Spring Boot application runs on 8080 port by default

Congratulation

Congratulation!!! Your first Spring Boot application is ready now for more fun stuff!!!

Note: If you face “Maven unknown error” while importing a project into Eclipse IDE, try this.

Found it Interesting?

Please show your support by 👏.

Disclaimer:

I myself have just started learning, Spring Boot. If you find any issues please feel free to post them in the comments section below. Thank you for reading so far 😄
Spring Boot + RabbitMQ: Processamento assíncrono com filas
By: Guilherme Milagre
Tags: Spring Boot, Tecnologia, Rabbitmq, Microsserviços

Learn more. Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Make Medium yours. Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore
Spring Boot + Kubernetes — Scalabilità con Horizontal Pod Autoscaler (HPA)
By: Andrea Scanzani
Tags: Java, Spring Boot, Kubernetes, Architecture

Learn more. Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Make Medium yours. Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore
Spring Boot 2.4.0 Docker化
By: Vic Chang
Tags: Spring Boot, Kotlin, Docker

誤以為創業很簡單的工程師 You will never be ready until you try to do it!
What is Reactive Programming?
By: Kathiriya Niket
Tags: Asynchronous, Reactor Project, Reactive Programming, Spring Boot, Functional Programming

Asynchronous and non-blocking:

Let’s look at an example of two people chatting through WhatsApp or any other social media platform.

Asynchronous & non-blocking communication

Tony sends a message to Mary.

Mary is busy at the moment. When she gets some free time, she will read the message and reply.

Meanwhile, Tony doesn’t have to wait for the reply. He can continue his work and he will be notified when Mary replies to his message.

This same methodology, when applied to programming, is called Reactive Programming. This way, independent API calls will not block the threads.

Message/Event-driven communication:

I mentioned that the data flows as a Message/Event stream in reactive programming. What does that mean? For that, first, let’s see the traditional (imperative) programming data flow.

Traditional data flow

Service-1 sends a request to Service-2 for some large resource.

Service-2 will prepare that resource. Meanwhile, Service-1’s thread will be blocked, and waiting for the response.

Then, Service-2 will send the entire data in one response.

Here, Service-1’s thread gets blocked even when it doesn’t need to. Plus, what happens if the huge response causes Service-1 to go out of memory?

Now let’s see event-driven data flow.

Event-driven dataflow

Service-1 will send a request to Service-2 for any resource.

Service-2 will immediately return the call.

Now, as Service-2 prepares the resource and sends it to Service-1 in small chunks of data.

Once the entire response has been sent, Service-2 will notify Service-1 that the response is complete now. (onComplete event as seen in the image)

Functional style programming:

It is a declarative style of programming rather than imperative (Similar to Streams API of JDK 8)

It makes code less complex, more predictable, and easier to test.

Makes it easy to work with lambda expressions.

Checkout this blog for more on functional programming: https://quickbirdstudios.com/blog/what-is-functional-reactive-programming-frp/

Backpressure support:

In the above scenario of traditional Service-1 and Service-2, let’s consider what happens if the resource sent by Service-2 is too large for Service-1.

The service-1 threads can be taking a long time to process. Service-1 threads were already blocked for the time that Service-2 took to prepare the response. Now, Service-1 will also need time to process that huge data.

Service-1 can go out of memory.

So there is no way for Service-1 to communicate with Service-2 regarding the amount of data that it can accept. This is called backpressure. How does reactive programming change this? Let’s see,

Backpressure support