fabiochiu/medium-articles huggingface dataset:
An Adulterer Gets Stoned
By: Jim Mcaulay
Tags: Aj Jacobs, Illumination, Jim Mcaulay, Humour, Humor

On the stoning of an Adulterer in New York City.

Photo by Kathy Marsh on Unsplash

In this Article we write about how A. J. Jacobs stoned an adulterer in New York City.

One day A.J. Jacobs decided that he was going to follow all of the over 700 rules that are mentioned in the Holy Bible. It took him over a year to accomplish and he wrote a book about it.

The Year of Living Biblically: One Man’s Humble Quest to Follow the Bible as Literally as Possible.

One of the rules he set out to follow was to stone an adulterer.

One day a man came up to him and asked him what he was doing and why he was dressed like that. He had not shaved his beard and was wearing sandals and a robe.

He explained what he was doing and the man said.

I’m an adulterer are you going to stone me?

This was an excellent opportunity to write this off his list. He took out the small bag of pebbles that he was carrying for just this purpose.

The man grabbed him, took the pebbles away from him and threw them in his face.

He picked up a pebble and threw it at the man thereby killed two birds with one stone.

He stoned an adulterer and he followed the eye for an eye commandment at the same time. It wasn’t exactly literal but he wasn’t going to have an eye poked out of loose a tooth.

And that is the true story of the stoning of an adulterer in New York City.
Your “friend”
Tags: Poem, Toys, Humour, Poets On Medium, Poetry

If it is plastic, metal, glass,

or the end of a bottle,

even if it’s realistic,

with veins and all,

or much bigger than me,

if it’s humming makes you shiver,

black or green or putridly pink,

lasts all night or until the

batteries expire,

I don’t mind.

But if it’s rubber,

hot-water-filled and

clasped tightly to your bosom,

I hate it ’til it hurts.
The True Story Of Biden’s Broken Foot
By: Rachael Ann Sand
Tags: Pets, News, Joe Biden, Humour, Humor

Blame the dog. Classic, Joe, classic. Dogs get blamed for farting, eating the last piece of pizza, and all manner of ill-mannered human behaviors. But I’m here to tell you Major is as innocent as any German Shepard.

If the president-elect didn’t injure his foot playing with his furbaby, what actually happened? The American people deserve to know. Afterall, the majority of us legit voted for him.

To get to the truth, let’s start with the lie. Here’s what CNN politics reported:

Three days after Thanksgiving this year, President-elect Joe Biden slipped and hurt his foot while playing with his dog, Major.

After debriefing with my top secret team I’ve uncovered the real story. It’s much less furry and a whole lot more scary. As most believable lies do, the advertised story has a nugget of truth in it. Joe was playing with his dog, Major, on the fateful night he fractured his foot.

However, Major was all tuckered out and napping under a tree when Joe sprung into action to chase an intruder. Apparently his security needs some beefing up because they’re leaving the 78 year old president-elect to fend for himself. Technically our future leader tripped over his sleeping dog’s tail in pursuit of a would-be, well, that’s the million dollar question.

Who was the mysterious intruder? A would-be thief, assassin, dog-napper, spy? The world may never know the intent of the real culprit in this tale of tail-tripping. That may be the very reason Joe lied about the injury. If the story of a security breach were to leak it would give Americans one more reason to worry and we’ve had it up to our necks with worry this year. Speaking of necks, thank goodness Joe only broke his foot.
The international vaccination program will be underway very shortly.
By: Will Medas
Tags: Covid 19 Crisis, Politics And Protest, Covid 19 Testing, Humour, Political Satire

The international vaccination program will be underway very shortly. According to national reports, over 50s will be first in line to receive this revolutionary and somewhat controversial new jab, developed and tested in a record breaking period of barely ten months. Groundbreaking work has obviously been achieved by leading scientists and all backers involved in developing this miracle cure, it may be too early for celebrations, but like many others I feel as thought the government has done a great job in controlling this current pandemic. It’s now feasible to foresee the new normal every politician was talking about ten months ago finally starting to mould into shape as early as next March, once all vaccination programs have been executed across the country that is, a year after the first initial lockdown.

So whilst we will still be encouraged to maintain social distancing in the mean time, and tier systems may potentially still be upheld across the country, many will undoubtedly flock to their local GPs and get in line to receive the latest in groundbreaking medical developments to have been rolled out this side of the equator. In the meantime it has been interesting to see how this vaccine has been marketed across the UK in particular. A while back I came across a study which was conducted back in July by Yale University if memory serves me right. This study was tasked with presenting a successful pro-vaccination campaign aiming to focus on particular dissident traits of individuals, so that through subtle coercive techniques such as using guilt or fear, would convince even the most stubborn anti-Vaxers to collaborate and fall in line.

Whilst Pfizer and Biontech only made the announcement regarding national distribution today, what I read has been at the back of my mind whilst watching the latest narratives and, whilst I haven’t been made to feel guilty yet that perhaps there is a strong chance that I will infect my mum with COVID-19 when I hug her this Christmas, it’s good to know that people are sceptical and are asking serious questions!

Am I worried that the jab will covertly track me with a microchip? No, besides 5g towers are far and wide, where I live at least. One thing is for sure however, I will be glad to be getting back to work real soon, regardless of whether I will need to carry a medical passport or not!
According To…
By: Thomas Mullen
Tags: Communication, Politics, Humour, Pentina, Planning

According To…

Photo by Suzy Hazelwood from Pexels

The plan’s not working. All the newspapers said it, though no spokesman had come forward to confirm or deny.

Those four words ambushed the governor as he spoke before the crowd. His response served to seal his fate.

“Which one?”

He stared blankly as the journalists scribbled, proving the point.
Jim McAulay🍁 Your fiction writer's Bio is featured on Illuminations homepage in Editor's Choice by Tree Langdon. I'm featuring a new writer BIO every couple of days. Join us on Slack and be part of…
By: Tree Langdon
Tags: Fiction, Illumination, Jim Mcaulay, Humour, Humor

Jim McAulay🍁 Your fiction writer's Bio is featured on Illuminations homepage in Editor's Choice by Tree Langdon. I'm featuring a new writer BIO every couple of days. Join us on Slack and be part of the Fiction Writer's Club!
For The Love Of Humanity, Stop Apologising!
By: Rachel Dodman
Tags: Celebrity, Funny, Humour, Society, Humor

For The Love Of Humanity, Stop Apologising!

Photo by Etienne Girardet on Unsplash

Rita Ora (a singer, she did Your Song — that one with the catchy bibbly bobbly backing) has recently apologised for having a thirtieth birthday party. It was apparently a ‘small’ affair, with thirty guests (one for each year, presumably). It was in a restaurant in London during lockdown. Restaurants aren’t allowed to open (except as food takeaways) and we are only allowed to meet one person who isn’t from our household — and that has to be outside. Even if she has a thirty person household, they shouldn’t have been in a restaurant.

Rita’s party was broken up by the police.

She has posted a three-paragraph apology on her Instagram page. She described how embarrassed she felt, how she has put people at risk and that she takes full responsibility for her actions. She strikes a very contrite tone.

But is Rita Ora actually sorry? Or does she feel she has to apologise to maintain her public image?

We hear it all the time. Politicians are forever apologising for tactless, unkind or downright idiotic things that they say. Mike Hedges (a Labour MP) described Brexit as being like “like getting divorced after 43 years. It might look better on the outside with all these young women available to you. But I think the reality may well be something different.” He later apologised.

Today, HSBC have said that they will apologise when they have their senate hearing about money laundering. So they are not sorry at the moment — they will be sorry by their hearing. Apologising must take some planning?

A website glitch wiped Currys PC World giftcards , leaving the owners or the cards unable to spend them. Guess what Currys PC World said? You got it. Sorry.

Dr Rosina Allin-Khan, a Labour MP, misused people’s data and used House Of Commons stationery for inapproprite purposes (it’s not allowed for campaign purposes). She was told to reimburse the costs and…can you guess? Yup. Apologise.

There has been an inquiry into Priti Patel’s behaviour. (Priti Patel is the UK home secretary.) The inquiry found that she had bullied the home office staff. So…she apologised.

Photo by Henrikke Due on Unsplash

Everyone is at it. The little list above were a quick search on the BBC News website. I could have continued giving examples until I had to apologise for the length of this piece!

I have had enough of it. I remember correcting my children for delivering meaningless apologies. Thes adults should know better!

According to Merriam Webster, sorry is a feeling of regret or penitence. I agree with them. These days ‘sorry’ and ‘apologise’ are used to mean “I’m sorry I got caught and I won’t get caught again.

That isn’t apologising and until famous people and corporations can apologise properly, I am not accepting them!

Ms Ora, your apology is unaccepted!
Lessons For Pabda!. Dear Pabda,
By: Sujata Dehury
Tags: Sarcasm, Humour, Food Humor, Fish

Dear Pabda,

The other day I met your celebrity cousin Hilsa. I have been reading so much about her these days. She is all over, across social media platforms. My Bengali friends singing paeans, writing testimonials like she is from the depth of the Caspian and fed only black caviar. And my costal Odia friends never getting enough of a proverbial ‘Ilishi jhola’ or a sukhua which is painfully salty and stinky.

Steamed Hilsa aka Bhapa Ilish!. Pic courtesy: Monalisa Patnaik, Hilsa lover and passionate cook who gets to eat the world’s best catch in her California home.

I too got carried away with her all pervasive and sustained PR drive. I decided to pinch a hole in my pocket and brought her home. But, I live far away from the Padma Nadi and had to be content with a catch from the Arabian. She reached home with lot of care. We washed her in filtered water, gave her a turmeric bath. She sizzled in hot mustard oil before plunging into that thin curry.

Here is a confession which may make you feel good. Hilsa gets most attention because she is an absentee most of the year. She comes back with a pregnant belly and creates a brouhaha every monsoon. You never do that. You are just so available. She always behaves like a celebrity and has clearly stayed away from massy events. She does special appearance in monsoon or a rare couple appearance on Saraswati Puja in Bengali households.

Hope you are jotting down the pointers.

I decided to give her a special treatment. Nigella seeds, green chili and grated ginger, all her regular companions were kept ready. Just to make her feel comfortable in my house.

And I didn’t want to disappoint her. I kept her in party spirit, slathered in fine yellow mustard paste, drenched in mustard oil, ornating her with green chilies and wrapped in banana leaf. I sent her for a lazy sauna bath. I know, reading all these is making you jealous already. But, what a disappointment she was. With treacherous bones across her body, she was a trap. She was fake and it hurt. And bland too.

You are more sorted. You could be thin, not as slender as her, but atleast you know how to arrange your bones neatly. Did I mention, her manager after two weeks of persuasion, finally gave me a ticket, a chance to make her my Sunday chief guest. I ditched my favourite mutton curry. I am still cribbing.

Come soon again, please. I promise, I will give you all that I gave to Hilsa and make you shine.

Text: Sujata Dehury
What If
By: Jim Mcaulay
Tags: Illumination, Jim Mcaulay, Humour, Poetry, Humor

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
Thank you for this piece. I have read and enjoyed some of David Sedaris' books in the past, and am coming back to writing myself, of late. I think he has a truly unique style and voice, so very funny…
By: Anthony Halliwell
Tags: Writing, David Sedaris, Blog, Humour, Writing Tips

Thank you for this piece. I have read and enjoyed some of David Sedaris' books in the past, and am coming back to writing myself, of late. I think he has a truly unique style and voice, so very funny and surely plenty of indispensable wisdom to impart.
Spring dependency management — A new approach to wire beans
By: Yağız Ünsal
Tags: Spring Framework, Java, Spring Boot, Dependency Injection, Spring

In this article, I will propose a new approach to inject Spring beans to our classes. Only a Spring Boot project is necessary. We’ll also use Lombok to avoid the necessity of getter and setter methods. When properly applied, we will get rid of all @Autowired annotations (we’ll only use it once — yes, once!).

So, let’s get into work…

First, let’s create a package in our project named “bean”. In this package, we create a class:

This is an abstract class. We’ll use it to distinguish our bean providers from other Spring beans. 2 event methods are added in case there is a need. We’ll use onAfterLoad() method. But, onBeforeLoad() is added as well.

Next, we create 3 bean provider classes. Of course, the number of bean providers is completely up to you.

These classes are annotated as @Component. Which means, these are Spring beans. Getter methods will be created by Lombok. Also, Lombok will create setter methods as well, but setter methods will have protected as access modifier. This is to prevent the classes from other packages to change our beans.

As you can clearly see, in bean provider classes, we list the beans we need. Thanks to Lombok, we don’t write getter and setter methods. We only declare the dependency we need, and do nothing more! We’ll do the binding later. Also, notice that with this approach, we can group our related beans in different bean providers. And, last but not least, it is worth to mention that a bean can be declared in several bean providers (meaning, there is no limitation such as a bean can only be defined in one provider).

In all bean providers, onAfterLoad() method is overridden. This method will be invoked by us later, when all of the beans defined in the provider are loaded. In this method, we assign the bean providers to the field of same class with name Beans. The definition of this class is followed:

This is the class where we declare all our bean providers and create their public static getter methods. The class is meant for static methods, so the constructor is private.
Spring: Bean Lifecycle
By: Deepak Jha
Tags: Spring Framework, Java, Spring Boot, Beans, Spring

In this blog, I will share my knowledge about the bean lifestyle, as we already discuss beans and their scope in my last blog, so I hope you now have a basic idea about the spring bean.

So, when the spring container starts there are few things happen, First Bean instantiated then the dependency injected, and then some spring internal processing occurs with the bean factory, and next, we have the option to write our own initialization code and after this point, Bean is ready for use in our application and at some point container will shut down.

I created this diagram to better understand the lifestyle of beans and also we will take a look at Init and Destroy method/hook.

Bean LifeCycle Method/Hooks

With the help of the bean lifecycle method, we can write our business logic or any custom code like bootstrapping data during bean initialization, also we can do the same thing while destruction of bean-like cleaning up the resources.

Bean-Lifecycle by XML configuration

When we use XML configuration for defining the bean, we have to use init-method and destroy-method attribute to define which method will call when the bean is instantiated and destroy.

Example :

In the web.xml configuration file, I created a bean name videoStreamingService and provided two attributes init-method and destroy-method and which will call the doSomeTaskOnInit when the bean is instantiated and doSomeTaskOnDestroy when the bean destroy.

Provided the web.xml to the spring Ioc container and shut down the container.

Output

Bean-Lifecycle by Spring’s Interfaces

We can implement Spring’s InitializingBean interface to run custom operations in afterPropertiesSet() phase:

output

Bean-Lifecycle by Spring’s Annotations
Versionar sua base de dados com Spring Boot e Flyway
By: Nataniel Paiva
Tags: Spring Boot, Flyway, Database, Spring

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
Flow of HTTP Request In Spring MVC.
Tags: Spring Boot, Mvc

My private Image

MVC-(Model View Controller) framework is an architectural pattern which is based on three main components : Model, View, Controller. MVC separates the business logic and presentation layer from each other. It was traditionally used for desktop graphical user interfaces (GUIs). Nowadays, MVC architecture has become popular for designing web applications as well as mobile apps.

Now what about flow of HTTP request in Spring MVC?

Everything is starting when we hit a URL in a browser. Working process is a request first come to the DispatcherServlet.

DispatcherServlet will ask Handler Mapper to identify which controller is responsible to handle this request. Handler Mapper will basically identifies which controller is responsible to process this particular request . For example: HomeController, LoginController , UserController.. It will go relevant controller and will look into the handler mapper or the method which is annotated with at the request mapping annotation with relevant URL. So once handle mapper will map this request to this particular handler mapper then handler mapper will return particular controller details to the dispatcher servlet . Now dispatcher servlet already knows which controller is responsible to handle the request. Then DispatcherServlet will send that request to the corresponding Controller.

Controller will basically responsible to process this request and it will create a model data and it will just return a view and model to the dispatchers. Here, a data can be in any form such as objects, strings, information from the database. Now dispatcher Servlet has a model kind of view especially don’t know which view it should map and it will consult a View Resolver . View Resolver identifies the location of actual view page , let us say if we are using JSP.File , it will basically identify where the JSP pages are located in our project. Now View Resolver will find a location of the pages , view pages and extension and then that details will be again returned to the dispatcher servlet. Dispatcher Servlet now send the view and actual content of view and model to the view component. Your component will merge model and view and it will return a plain HTML page . And dispatcher servlet will finally send that HTML page or response to the browser . So this is the typical flow in spring MVC application.
Implementing Caching Service in Spring Boot using Guava Cache
By: Amit Khule
Tags: Programming, Spring Boot, Guava, Rest Api, Caching

Implementing Guava Cache Example

Let’s see how we can implement a simple Cache-Store using the Guava Cache library.

The rest of the article details all the steps we need to implement Caching Technique. If it is helpful, you may also download the final source code from GitHub Link — Implementing Guava Cache

Step 1: Create a Spring Boot Project

We need one Spring Boot project. The basic skeleton can be created quickly by using https://start.spring.io/ as below,

Step 2: Write HTTP GET REST API

Write one sample REST API as detailed below. In this API, we are simulating a backend service call by adding an intentional wait time. The next step will introduce the Guava Cache to cache the API response and improve the overall latency.

When we build and run this application, it will produce the below output, which shows some latency as each time call is sent to backend service to fetch data,

Step 3: Add Guava Dependency

In build.gradle file add Guava library to the list of dependencies as,

compile group: 'com.google.guava', name: 'guava', version: '30.0-jre'

Step 4: Define a Class to provide Cache-Store for any generic type <T>

Let’s call this class CacheStore, which can help us build a Cache instance for any generic type

Please Note: expireAfterWrite() provides the ability to invalidate the Cache Records accordingly to the supplied parameters.

CacheStore.java

Step 5: Define a Java Bean to generate a new Cache Store of record type Employee

CacheStoreBeans.java

Step 6: Modify ApiController Class to implement Caching for Employee records

Here in this step, we will store Employee records in Guava Cache.

Please Note:

For the first request, we will not find the Employee record in Cache. And we need to call backend API to fetch the Employee record. (Here, the backend API has an intentional delay to simulate an HTTP call over the network.) The fetched Employee record is must be stored in the Cache first before returning it to the consumer. For subsequent requests, we will find the Employee record in the Cache. We can immediately return the cached Employee record in the response by skipping the backend API call. In Step #5, we had created Cache-Store with an expiry duration of 120 seconds. Therefore, the LoadingCache will retain the Employee record only for 120 Seconds. Guava Cache will keep track of time and invalidate/remove the Employee record from Cache by itself post 120 seconds.
Spring Boot 006: Encrypt/Decrypt Application Properties via Jasypt
Tags: The project, Spring Boot, the source code at Github, Jasypt, Spring

Jasypt(Java Simplified Encryption) is a Java library that allows the developer to add basic encryption capabilities to projects with minimum effort, and without the need of having deep knowledge of how cryptography works.

0. Prerequisites

To encrypt a value via Jasypt, we’ll be using some CLI (Command Line Interface) tools that have been supplied by Jasypt. You can simply download these from the project’s Github repository.
Effective Technique to Implement LoadingCache in Java Spring Boot using Guava
By: Amit Khule
Tags: Java, Programming, Spring Boot, Guava, Caching

This article demonstrates an effective technique to implement LoadingCache in Java Spring Boot Service using Google Guava Cache API.

Background

In my previous article, I have explained the importance of using the Cache and then demonstrated a way to implement Guava Cache in the Java Spring Boot service.

In that example, we first checked whether the Record exists in Cache. If the Record is found in Cache, we skipped the backend service call. Otherwise, we fetched the Record details using the backend service and stored them in Cache for future use. That seems like a lot of manual handling. Can this be more simple?

Guava does provide another easy way for Cache management thru LoadingCache. A LoadingCache is a Cache built with an attached CacheLoader. We configure CacheLoader by pointing it to the backend service, which can then be used to load values using a KEY when it is not already present in Cache.

By managing retrieval and storing of records by itself, the LoadingCache makes it easier to implement the entire Caching mechanism. We only need to call method get(K), and it will either return an already cached value or atomically load a new value into the Cache using the Cache’s CacheLoader.
Spring Security5 を使ったソーシャルログインの実装
By: Yasuhiro Yamano
Tags: Spring Boot, Oidc, Oauth2, Spring Security

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
Introduction of Hibernate
By: Dilusha Amarasekara
Tags: Java, Spring Framework, Hibernate, Spring Boot, Spring

Hibernate Overview

Hibernate is a framework for persisting or saving Java objects in a database. if you want to download the hibernate framework. You can visit this database www.hibernate.org. hibernate can easily create applications and store retrieve objects from the database.

· Hibernate can handle all of the low-level SQL codes.

· Hibernate can minimize the amount of JDBC code you have to develop.

· Hibernate provides the Object-to-Relational Mapping

So, I’ll explain about ORM using this example.

So, if you want to tell how to hibernate maps java class or object to the database. you have to map your java class to a given database. in this example, there is a class called Student. It has four fields id, firstName, lastName, and email. And middle has a hibernate framework. Then the left side has an actual database table. Also, it has four fields like a java class such as id, first_name, last_name, email. Also, it mentions the data types of the particular fields. So we have to say to hibernate framework this Java class Student maps to the given table. And have to set up a one-to-one mapping between the fields and actual columns in the database.

Now we want to set up this mapping via a configuration file. Using XML or can set it up using Java annotations.

So, now we look at how to the saving a Java object with Hibernate.

· First thing is we want to create a java object.

Student hiberStudent = new Student(“dilusha”, “chamod”, “dilusha@gmail.com”);

You can see I mentioned the firstname, lastname, and email.

· Now we have to save this object to the database. so here we used session, which is a special hibernate object.

int stuId= (Integer) session.save(hiberStudent);

In this code, the data is passed to the object. Hibernate will take the java object on those mapping that has been defined earlier. Hibernate will take that information and store it in the appropriate table, in the appropriate columns. These all the things are worked by the hibernate framework.

We mention the session.save() then Hibernate will return the actual ID that’s been assigned to that entry.

Now we look at how to retrieve from the database using the primary key. We use session.get statement.

Student student = session.get(Student.class, stuId); so, hibernate find the Student class and save the data to the particular Id called.

stuIdQuery query = session.createQuery(“from Student”); List<Student> students=query.list();

If you want all the Student objects. Then you can get a list of those Student objects. That query name is “from Student”. Then it all the queries past to the query variable then query.list() list all the Student objects. . So this work we want to small step to finish this work. Also, hibernate minimizes a lot of the low-level JDBC code you have to write in the past.

Thank You!

Dilusha Amarasekara
Dawn of my Learning Journey
By: Sushree Soumya Mishra
Tags: Java, Spring Boot, Jpa, Hibernate

A little story before I start on the technical part…

Why am I writing this?

In the Covid era, I have no one to talk with, no one for a tech talk over tea and absolutely no one with whom I can share my crazy application ideas. Also, no one to listen to my learning plans. I miss going to office…It’s been a long time!

I am bored of being bored. I am bored of talking to myself. Now I wanna write for myself which I can later read to myself… Sounds crazy? Trust me, it’s not!

It actually works! I feel extremely happy and proud when I look at my old tech article.

So, my plan is to document my learnings (what, why, how, etc.) which would give me immense happiness after 5–10 years. When I’ll look at this post and the upcoming ones, I’ll enjoy re-reading them to myself. Well, it’s like tech-talks with myself! And of course, to stay away from boredom.

Why I came up with such a crazy plan?

Long long back, I had worked on struts and JDBC. I had become a pro in that. Then for around 2 years, my projects didn’t have any frameworks/DBs. Hence, I was residing in dark (the twilight, actually). All of a sudden, I realized the need of learning Spring/Springboot along with Hibernate and JPA. I was clueless… Easy thing first! So, I started learning Springboot and then went ahead with Hibernate. Eventually, I had my hands dirty with webservices and a lot more.

Within a week, I had learnt enough.

How did I do it? Mr. Google, of course!!

I had learnt enough to work on a project that used Springboot, Hibernate and JPA. Till date, that knowledge was just enough! I was able to work comfortably on my project tasks.

But… Honestly, it wasn’t really enough… I was a master of none!

That’s when a I dreamt of doing something constructive.

And my learning journey started…

In my upcoming posts, I would be sharing the idea of my application and the technologies that I would use. For each step, I would explain what, why and how I have done it.
Spring boot logging proper SQL statements/logs while using Hibernate JPA.
By: Maheshwar Ligade
Tags: Java, Microservices, Programming, Hibernate, Spring Boot

Most people will laugh by reading the title of this blog post and many people think what is this, already we know this is very simple by enabling flag but here is tricky. There are three ways we can log SQL statements,

spring.jpa.show-sql:

This is the standard property 99% of people know and all of us are used this property to enable and disable the SQL statement in logs. To enable/disable we are including this property in the application.properties file.

spring.jpa.show-sql=true

The disadvantage of this logger is that it will just show us this log

Hibernate: insert into patient (id, name, address) values (?, ?, ?)

From this log, we know that some data inserted but what data inserted we don't know. It doesn't show us the parameter values.

2. spring.jpa.properties.hibernate.format_sql:

There is one more additional thing we can do to prettify the output using the below properties.

spring.jpa.properties.hibernate.format_sql=true

This formats the statement and prettifies it by adding indentations, so it gives a clear idea in an SQL way 😊,

Hibernate:

insert

into

patient

(id, name, address)

values

(?, ?, ?)

3. Using Loggers:

Another way we can do this by using a logger level. if you come across some crucial PROD bug then definitely you are aware of how you can utilize this feature of spring boot.

logging.level.org.hibernate.SQL=DEBUG

logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE

This gives logs in detail with each parameter value and datatype.

2020–12–19 00:18:16.016 DEBUG 1096 — — [io-8080-exec-12] org.hibernate.SQL : insert into patient (id, name, address) values (?, ?, ?)2020–12–19 00:18:16.049 TRACE 1096 — — [io-8080-exec-12] o.h.type.descriptor.sql.BasicBinder : binding parameter [1] as [BIGINT] — [1]

2020–12–19 00:18:16.047 TRACE 1096 — — [io-8080-exec-12] o.h.type.descriptor.sql.BasicBinder : binding parameter [2] as [VARCHAR] — [Mukesh]

2020–12–19 00:18:16.047 TRACE 1096 — — [io-8080-exec-12] o.h.type.descriptor.sql.BasicBinder : binding parameter [3] as [VARCHAR] — [India]

Loggers are a really simple and elegant way to debug or trace out the flow and find the root cause.

Github Repo

More such articles:-

https://medium.com/techwasti

https://medium.com/techwasti/spring-boot-liquibase-to-manage-database-versioning-ffa2b713d29c

https://medium.com/techwasti/spring-boot-thymeleaf-hello-world-example-11bc00bb22b4

Let’s connect on Stackoverflow, LinkedIn, Facebook & Twitter.
All about @RequestHeader in Spring Web
By: Satya Samal
Tags: Spring Boot, Http Headers, Annotations, Http Request, Spring

Here is a basic syntax of @RequestHeader annotation. In this value of key “firstName” will be taken from the incoming request header and will be mapped to the variable “name” of type string. No matter how many keys are there in the incoming request header spring will try to search for the key which is equal to “firstName”.

RequestHeader can have four optional fields :

name (String) : tells the name of the request header key to bind to and it’s default value is empty string (“”)

tells the name of the request header key to bind to and it’s default value is string (“”) value (String): it is an alias to name

it is an alias to name required (Boolean) : it tells whether the header is required or not. By default it’s value is true so if you want any header to be optional then you should set the required field as false.

it tells whether the header is required or not. By default it’s value is so if you want any header to be optional then you should set the required field as false. defaultValue (String) : it is used to assign a default value to a header key. so in above case if “firstName” is not present in incoming header then default value of “firstName” will be “bob” so name will have a value of “bob”. If defaultValue is not provided then its default value will be “

\t\t

\t\t

\ue000\ue001\ue002

\t\t\t\t

”.
Spring: Bean Scopes
By: Deepak Jha
Tags: Java, Spring Boot, Scopes, Beans, Spring

In this blog, I will share my knowledge about the sping bean scopes.

As you already know Bean is a simple java object and when it is created by the Spring Container, that refers to a Spring Bean.

Scope refers to the lifestyle of a bean which means, how long the bean will live, how many instances will be created, and also how will bean shared in the spring environment.

1. Singleton Scope

The default scope for the bean is a singleton that means the spring ioc-container will create only a single instance of that bean and it is cached in memory, and all request to that bean will return a shared reference to the same bean and also any changes to object will be reflected in all references to the bean.

Example :

2. Prototype Scope

When we explicitly declare a bean scope to prototype scope then the spring IOC-container will return a different instance every time it is requested from the container.

There are three more scopes that are used in the web app, and I will publish another blog on those bean scopes.
Spring Boot Liquibase to manage database versioning.
By: Maheshwar Ligade
Tags: Programming, Microservices, Spring Boot, Liquibase, Java11

Liquibase:

In this article, we will demonstrate to you how we can use liquibase with spring boot to manage the database schema versioning.

Liquibase Community is an open source project that helps millions of developers rapidly track, version, and deploy database schema changes.

Manging database versioning is a really crucial part and the team has to manage those. In the Java community, there are two tools available flyway and liquibase. Database schema migration performed on a database whenever it is required like want to revert the change rollback to some nth version. Liquibase supports most of the major databases and different types of format for schema change files like XML, SQL, YAML, JSON. It is database vendor-independent means it does not depend on any DB specific syntax. It can generate database change documentation.

Spring Boot with Liquibase:-

We can use liquibase with spring boot, you just need to add the dependency into the pom.xml file.

<dependency>

<groupId>org.liquibase</groupId>

<artifactId>liquibase-core</artifactId>

</dependency>

By default Liquibase using the primary datasource. If you wish to use a different datasource for Liquibase then you can configure using the below configuration,

spring:

liquibase:

enabled: true

user: liquibase_test_user

password: liquibase_test_password

Tech Stack:

Spring Boot 2.4.1

Thymeleaf 3.0.11

Tomcat embed 9.0.14

JUnit 5

Gradle

Java 11

h2 database

Liquibase

Visual studio code

Let us go ahead and hit the https://start.spring.io/ and generate the project and open it in any editor.
This is actually the first time I read a post and I don’t agree with it completely.
By: Joao Elvas
Tags: Java, Spring Framework, Spring Boot, Lombok, Spring

This is actually the first time I read a post and I don’t agree with it completely.
Using H2 console during test debugging in Spring
By: Hubert Schumacher
Tags: Intellij, Debugging, Spring Boot, H2, Testing

How do I use H2 to verify the database content during debugging sessions of integration test?

Configure your Spring project to enable H2 console

The application.yml file can be configured as follows (example). If you use application.properties, the same settings would apply but in the typical properties format.

spring:

datasource:

type: com.zaxxer.hikari.HikariDataSource

url: jdbc:h2:mem:myDb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE

name:

username: sa

password:

hikari:

auto-commit: false

h2:

console:

enabled: true

settings:

web-allow-others: true

trace: true

Set your Breakpoints

In you IDE, when setting breakpoints, verify that the breakpoints you set, suspend the Thread only and not all threads. All Threads would also suspend the H2 server thread.

In Intellij this is done my right-clicking on the Breakpoint and select Suspend: Thread.

Then you can run your test in debugging configuration and inspect the database content with the H2 console.

Inspect data with H2-Console

If note configured differently, H2 console will be available through the url

Now you can login to the H2 server and access the database content while selecting the data-source url and the username and password from your configuration in application.yml.

Happy debugging!!
Spring Framework
By: Yash Behara
Tags: Computer Science, Spring Boot, Full Stack, Web Development, Software Development

If your career/interest has something to do with Java, then this one is for you. Spring Framework is an open source Java Application Development framework with which Web applications, Data base driven applications and Enterprise applications can be built.

Developing an application is not that simple. At least not that simple as a White Hat Jr advertisement!. It takes a lot of effort in coding, then efficient testing and then finally deploying in a way so that others should be able to make improvements wherever necessary.

Well , to be precise.. what does spring framework actually do ?

Jar files generated are relatively smaller in size. Logic is loosely coupled , meaning one segment of code can be easily modified without much effort and effecting other segment. It takes care of Object creation and initialization and its dependencies. Makes the life of a unit tester comfortable . Provides all the necessary sources for easy unit testing. Provides configurable security and logging features.

If you want to learn more about various spring modules : Spring MVC, Spring REST, Spring Boot and Spring Data
spring Vs. spring boot
By: Ismail Alabou
Tags: Spring Framework, Spring Boot

spring Vs. spring boot

While the Spring framework focuses on providing flexibility to you, Spring Boot aims to shorten the code length and provide you with the easiest way to develop a web application. With annotation configuration and default codes, Spring Boot shortens the time involved in developing an application. Ismail ALABOU Dec 18, 2020·2 min read

Spring Boot is a module of Spring Framework. It allows us to build a stand-alone application with minimal or zero configurations. It is better to use if we want to develop a simple Spring-based application or RESTful services. Spring Framework is a widely used Java EE framework for building applications.

spring framework architecture

spring framework modules

The Spring framework comprises of many modules such as core, beans, context, expression language, AOP, Aspects, Instrumentation, JDBC, ORM, OXM, JMS, Transaction, Web, Servlet, Struts etc.

spring boot

architecture

use

It is used to create stand-alone, production-grade Spring Based Applications with minimum efforts. … It is developed on top of the core Spring Framework. Spring Boot follows a layered architecture in which each layer communicates with the layer directly below or above (hierarchical structure) it.

Happy reading :)
Spring Boot 005: Swagger 3.0 Implementation
Tags: Spring Boot, Swagger Ui, Swagger, the source code at Github, Spring

Hello. I’ll be introducing a simple yet great documentation tool called Swagger. If you’ve come across this article you probably know what Swagger is and simply wondering how to implement it or what more you can do with it. Just hang on, this one gonna be quick. Well, at least for you.

logo

0. About

The official website defines Swagger as a tool that allows you to describe the structure of your APIs so that machines can read them. The ability of APIs to describe their own structure is the root of all awesomeness in Swagger. Why is it so great? Well, by reading your API’s structure, it can automatically build beautiful and interactive API documentation. It can also automatically generate client libraries for your API in many languages and explore other possibilities like automated testing.

So let’s dig in.

1. Implementation

Add the following dependencies to the project’s pom.xml file.

<!--Swagger-->

<dependency>

<groupId>io.springfox</groupId>

<artifactId>springfox-boot-starter</artifactId>

<version>3.0.0</version>

</dependency>



<dependency>

<groupId>io.springfox</groupId>

<artifactId>springfox-swagger-ui</artifactId>

<version>3.0.0</version>

</dependency>

<!--Swagger-->

To enable Swagger, you need to create a Configuration class as such:

@Configuration

public class SwaggerConfig {

@Bean

public Docket api() {

return new Docket(DocumentationType.SWAGGER_2)

.select()

// .apis(RequestHandlerSelectors.any())

.apis(RequestHandlerSelectors.basePackage("com.tahaburak.atem.controller"))

.paths(PathSelectors.any())

.build();

}

}

By pointing the package of controllers, we’re preventing Swagger to list default controllers implemented by Spring itself.

So let’s run the application and visit the following URL on the browser.
Reactive WebClient
By: Aftab Shaikh
Tags: Spring Boot, Reactor, Spring Webflux, Spring

Spring WebFlux provides the reactive WebClient to make asynchronous api calls. It is fully non-blocking. Things I like about WebClient is it integrates well with reactor api providing very readable code and it is configurable in every way, which we will see in a minute.

Let’s start with creating an instance of the WebClient. There are two ways to do so:

Using WebCient.create() or WebClient.builder() functions Autowiring the WebClient.Builder Bean which spring provides

Once created, the WebClient is immutable which makes it thread safe. You can use webClient.mutate() to reconfigure it and get a new instance.

As we have created our WebClient, now let’s make an api call.

That’s all. Only with four lines of code we are able to make a GET api call. Let’s break down the code and look at individual parts

get() method specifies that it’s a GET api call uri() takes the uri string. You can also use another flavour of uri() which takes a function allowing you to configure the uri using UriBuilder retrieve() method is used to retrieve the response body. bodyToMono(Customer::class.java) is really interesting. It uses the Spring Codecs to deserialize the data into required domain class. More on Codecs; later in this blog

Similar way, we can make the following post api call.

The only difference here is bodyValue() method, which we use to send the request body
Let’s develop an Ecommerce Application from Scratch using Java and Spring
By: Nil Madhab
Tags: Java, Spring Boot, Backend Development, Ecommerce, Technology

Overview of our Backend Application

In this Spring Application following are important packages that you have to know before starting.

This is the spring architecture. The outside world calls the REST Apis, which interacts with the Service. Service calls the repository. The repository interacts with the database. We follow this pattern to make the codebase maintainable, instead of having spaghetti code which can be a nightmare in long term.

Let's look at first Rest controllers

Controller

The User Controller class provides two HTTP methods GET and Post. The Get mapping function return a complete list of Users and the Post Mapping Function saves the new user profile in the Database.

As we can see UserControllers has a reference to UserService.
Environment Variables In Spring Boot Application
By: Balaji Srinivasan
Tags: Spring Boot, Configuration, Java, 12 Factor

Spring Boot lets you externalize configurations for our application. Let’s take a simple application that connects to the database and perform some operations on it. The standard configuration for this kind of app would be the database related details. Below is one sample `properties` file

Like this, we might have more properties specific to our application also which we want to have as dynamic configurations that can be passed when application startup. In order to have these have different across different environments like dev, staging, production. Spring boot provides us with option to have environment-specific files with different values for different environments.

Below are a few common practices developers follow which has their own pros and cons

Commit secrets in these files as part of the codebase

Commit only local configuration in the codebase and as part of deployment pipeline copy environment-specific files from the different repository and build the package

If we are having separate profile files then we might need to have separate start-up scripts for each to ensure the right profile details are passed. If we are copying files at the time of the build for any change in secrets or configurations we might need to build the package again to take effect.

According to 12factor apps it’s good practice to store configurations in environments.

How can we achieve this?

We can avoid multiple property files and have only one file as below

The above helps in multiple ways

No need to rebuild the package again if there is any change in configuration.

One common property file versioned as part of the code base.

Build pipelines would be generic. Same builds can be used across all environments

When running as containers

If we are running our application as containers we need to pass the environment variables while starting the application. This can be taken care of by a deployment pipeline. If there is a change in value just a restart of the container is enough

When running as fat jars

If we are running our application as normal jars then the best practice would be to set the environment variables as part of the host machine and start the application.

What about local development/tests

For tests, I would recommend having a dedicated properties file. For local development, we can do it in two ways.

Have one `.env` file in local and `source` them before starting the application

We can give default values to properties if not present in environment as spring.datasource.username=${DB_USERNAME:username}

The key thing to note here is the deployment process. I will cover a detailed blog on how the deployment pipeline can be done for such a setup of spring boot application.

Cross Posted from Personal Blog