Spring Boot @RestController Action Returning java.util.Optional

Recently, I wondered what would happen if a Spring Boot RestController returned a java.util.Optional instead of a regular POJO.

I invested 30 minutes of my life to find out, and created an over-engineered example on GitHub.

Here is the controller.

@Slf4j
@RestController
@RequiredArgsConstructor
public class MusicController {

    private final MusicService musicService;

    @GetMapping(path = "/value")
    Album getValue(@RequestParam("isNull") boolean isNull) {
        log.info("Request album value (is null: {})", isNull);
        return musicService.getAlbumAsValue(isNull);
    }

    @GetMapping(path = "/optional")
    Optional<Album> getOptional(@RequestParam("isNull") boolean isNull) {
        log.info("Request album optional (is null: {})", isNull);
        return musicService.getAlbumAsOptional(isNull);
    }
}

The first question I had was if Spring Boot would even start up. You never know. It does, and with this hurdle out of the way, here’s the output of a couple of curl commands.

~ % curl -i 'http://localhost:8080/value?isNull=false'   
HTTP/1.1 200 
Content-Type: application/json
Transfer-Encoding: chunked
Date: Sun, 24 Jul 2022 08:24:50 GMT

{"artist":"Insomnium","title":"Winter's Gate","genre":"Melodic Death Metal","year":2016} 

~ % curl -i 'http://localhost:8080/value?isNull=true'    
HTTP/1.1 200 
Content-Length: 0
Date: Sun, 24 Jul 2022 08:24:55 GMT
 
~ % curl -i 'http://localhost:8080/optional?isNull=false'
HTTP/1.1 200 
Content-Type: application/json
Transfer-Encoding: chunked
Date: Sun, 24 Jul 2022 08:25:00 GMT

{"artist":"Insomnium","title":"Winter's Gate","genre":"Melodic Death Metal","year":2016} 

~ % curl -i 'http://localhost:8080/optional?isNull=true' 
HTTP/1.1 200 
Content-Type: application/json
Transfer-Encoding: chunked
Date: Sun, 24 Jul 2022 08:25:06 GMT

null

Everything works as expected except for the null-case with the Optional. It returns the string “null” instead of nothing.

The moral of the story: Do not return java.util.Optional from a @RestController, or you need to do more work to unpack it.

Thank you for reading.

MacBook Air M1 Apple Silicon Sleep High Power Consumption?

When I first got the MacBook and put it to sleep on battery, as one does, I wondered why the energy store had lost a surprisingly high amount of charge after just a couple of days of sitting on a shelf untouched, lid closed. Now that I have a power meter (almost a year later), I was curious and hooked up the plugged-in computer to it. As you can see from the title image, the result was 2.3 frigging watts. But why?

Given this number, I wanted to open this blog post with the following statements.

Here is an interesting fact for you. The most power-efficient computer of the past decade allows itself over 2W of power while it sleeps. Yes, two frigging watts. Sleeping.

Being a curious nut, I did some more digging and then overhauled this blog post accordingly. But first, let me continue with my original vision of this little rant.

This is time travel, my friends.

Read More »

The Effects of Burnout – Personal Report About Navigating a Crisis

If you are one of the few followers of my blog, then, first of all, thank you. Secondly, maybe you are wondering why I have not been writing about any programming topics lately, given the name of this blog. Perhaps you only started following recently and like the gaming content. Whatever your reason, my main focus has always been on software development topics of any kind, and this element has been lacking for quite some time.

Out of the 11 posts this year (at the time of writing), only five fall into the programming category. And if I’m being honest, I have spread two more extensive topics across those five blog posts to potentially get more clicks – although the separation also makes sense. Before I digress too much, the short version is this: I am actively neglecting the original premise of my blog, yet I still want to produce content. There is a reason, and despite that somewhat lighthearted title, it is a serious topic.

Note: Before I changed the title to what it is now, it was “Yo, CODE-Slinger! You Now a GAME-Slinger? No, I’m Having a Dance With Burnout“

Although this report is based on my personal experience with the subject, it is not about me. Nobody on the Internet is interested in me, and I am not delusional enough to think otherwise. Treat it as a biased case study that I sincerely hope can be a motivation for other people going through a similar thing. The light at the end of the tunnel can be an exit.

The following two sections elaborate a little on The Codeslinger origin story. If you are only interested in the meat, skip to “Dance With the Burnout”.

Read More »

Cyberpunk 2077 Ending Review

When I published my Cyberpunk 2077 review last month, I had not yet finished the game. Based on what I had played until that point, I still felt confident in my opinion – hence the review. I beat the game a couple of weeks later and have watched all possible endings on YouTube (no, I did not play them all myself). My general stance on the game has not changed, but I am even more convinced that Cyberpunk is a character and narrative-driven game, first and foremost.

Before I go on, beware that I use this blog post to talk freely, something I avoid in my usual reviews. I will drop a few spoilers, and although I try to stay as vague as possible, there will be a few hints here and there. With a little more knowledge and research under my belt, I will also briefly return to gameplay and the technical aspects of CD Projekt Red’s ambitious creation.

Read More »

Cyberpunk 2077 Review (Xbox Series X Next-Gen Update)

To continue, press “B”.

To continue, press ”=”.

I hate when games do this, and Cyberpunk 2077 does it twice when starting for the first time. It greets you with two screens that you must dismiss with the push of a button before you get into the menu. Why, CD Projekt Red? Why? That is not the kind of a first impression you want. It makes for good variety in the introduction segment of my reviews, though 🤷.

(I later discovered that the first “screen” is an intro video. It just does not appear to be one in the first seconds. I am so used to games starting with a pointless screen to dismiss that I immediately canceled the video without knowing and landed on the actual screen to click away.)

Cyberpunk 2077 is coming to its second birthday, and the hype surrounding it and CD Projekt Red came crashing down hard on last generation’s Xbox One and PS4 consoles.

(Like the meteor wiping out all dinosaurs about 66 million years ago.)

CDPR has been very busy since then, and in February 2022, they finally released the next-gen update for current-gen (🙄) consoles. This finally incentivized me to purchase a copy for myself and see if this game is as good as it could have been without its many issues at launch. According to recent reports, I am not the only one doing so.

Unlike the Witcher games, CDPR decided to go with a first-person experience for a deeper immersion into the colorful yet dark and gritty world of Night City. The game’s art style is reminiscent of The Ascent, a twin-stick shooter I played last year. In contrast, Night City is a vast Open-World metropolis with a few rural places surrounding it. Geralt’s companion Roach has morphed into a car, and dirt roads and farm tracks have been paved over and are now asphalt. You can walk, drive, or use fast-travel stations spread across town to get around.

In its simplest form, you can reduce the combat system to be just a Shooter. Cyberpunk 2077 adds a couple more mechanics on top of that for more variety if you choose so. You can go the stealthy and non-lethal route or become a proficient hacker (aka Net-Runner). I am a simpleton, so my character is a tank that sh*ts bullets (although I also like to sneak when I can). Despite the options, from what I have seen, there is no way to play the game without ever firing a gun. Hacking is more than manipulating computers. It seems like everybody is somehow connected over an unprotected Wi-Fi, and you can utilize a person’s cyber implants against them. Ever heard of 2FA 😉?

CDPR has shown in The Witcher games that they are masters in storytelling. You can find the same mastery in Cyberpunk, which I was most interested in. You will meet many different characters with their own traits and agenda. There is a lot of action RPG stuff to do, a skill tree, an inventory – the typical Open-World role-playing experience, if you will.

Let’s get into the details, shall we?

Read More »

Why are Some Console Game Controls so Terrible?

One of the “PC Master Race” issues with console gaming is the controls. I certainly was among them, and the more I play on a console, the more I keep coming back to this topic. 2021 was the first year where I spent the majority of my time playing on an Xbox Series console. Everything I tried during that year was okay, or it was still new enough to me that I could not differentiate between good and bad controls. On the PlayStation, I only played Horizon Zero Dawn, and I found it to be one of the best controller input implementations out there. In 2022, I have played fewer games in total in about the same period. Still, a higher percentage of them frustrated me with their implementation of analog-stick movement to the point where I was about to give up or actually gave up playing the game.

Why is it so hard for some developers to figure out an enjoyable controller feeling? Am I the only one noticing this, or are long-time console players just used to it? Let me take a step back and explain.

Read More »

Horizon Forbidden West Review (PS4 Pro)

After a bit of “Bla Bla”, I opened my Horizon Zero Dawn review with the following statement.

Best. End-of-the-World Story. Ever.

In the later parts of the review, I summarized the overall experience like this.

Horizon Zero Dawn feels excellent. It is one of those games that makes you feel empty once you beat it and put down the controller.

Both quotes express an extremely high bar of quality that Forbidden West is going up against. I am delighted that Guerrilla Games did not disappoint and delivered an incredible sequel that improves the experience in almost every aspect. Aloy’s second adventure has a couple of downsides resulting from modern Open World side activity design. However, compared to the exceptional setpieces you encounter during the main missions and the core gameplay, these are minor gripes you might choose just to ignore.

Forbidden West ups the ante further regarding the elements that matter to me in a modern (action) adventure game. It will be a benchmark in storytelling, character, and mission design. Zero Dawn was already excellent when it came to cutscenes. Lacking were only the dialogue sequences with other characters. Forbidden West changes this dramatically, and it looks and feels so much more organic now. Other key gameplay elements have also improved, like overriding Tallnecks or exploring Cauldrons. But more on that later.

Lucky me, I did not have to wait five years to enjoy this game as I did with Zero Dawn. However, were I inclined to get the absolute best experience, I probably would still have to hold out that long. A PlayStation 5 continues to be unbelievably hard to come by in Germany. But not to worry, there was no need for me to get into a crouching position again and hide in the shadows while I watched somebody play on YouTube. Horizon Forbidden West still looks and plays great on the PS4 Pro. Keeping in tradition with my first Horizon review, I wrote the first words on April 23, 2022. I might actually get this review done before the year ends 😅.

Read More »

Horizon Zero Dawn Review (PS4 Pro)

Let me start this review with a big fat spoiler: Horizon Zero Dawn has one of the most beautiful worlds and world-lore ever conceived. The period that the authors cover is mind-blowing. Never has an apocalypse, the events that lead up to it, and what happened afterward been stretched so far apart as in Horizon Zero Dawn. It is called a post-post-apocalypse scenario for a reason.

Best. End-of-the-World Story. Ever.

There, I said it. Feels good. I had this one on my chest for a very long time while I was procrastinating instead of crafting this review as promised in My Year in Video Gaming 2021 story.

(Takes a deep breath <inhales> … <exhales> and starts from the beginning.)

As I start writing this review, February the 6th, 2022, Horizon Forbidden West is just around the corner. Five years earlier, also in February, Guerilla Games released a completely new franchise that became an immediate success. It was one of those games that are said to exist only on PlayStation – a narrative-driven single-player adventure with an incredible focus on detail, quality, and polish. My kind of jam. But there was a slight wrinkle, though. As a PC player that had no intention of purchasing any type of console, and Sony not yet being in the business of also releasing their flagship titles on PC meant there was no point in waiting for a port. What does a ravenous gamer do in such a situation? He carefully presses CTRL and sneaks into a dark corner, hiding and unable to be seen by other PC players. He then shamefully turns to a trusted YouTuber and watches the spectacle in absolute awe and with envious contempt for himself.

About five years later, the former greedy PC gamer has now turned to consoles for his fix. Consequently, it was about time to experience Horizon Zero Dawn for myself. I have raved about this masterpiece to my sister, and she ended up buying it but then sat on the PlayStation while it gathered dust. To satiate my hunger, one day, I grabbed my PS4 Pro in one hand, my sister in the other, tossed both in the trunk of my car, drove home, and we ended up enjoying the game together. Good things come to those who wait, and I have waited long.

(No PlayStations have been hurt in this depiction of events.)

Let me dive into the details in my usual manner and tell you what I liked about Horizon Zero Dawn and what elements were not so optimal.

Enter the review
Read More »

Simplify Spring Boot Access to Kubernetes Secrets Using Environment Variables

This blog post is a follow-up to a previous blog post titled “Simplify Spring Boot Access to Secrets Using Spring Cloud Kubernetes“. Despite the downsides I mentioned, I already hinted at a more straightforward solution that utilizes environment variables. The plan is to get everything into the Pod with as little configuration effort as possible.

So, I promised a twist, and here it is, thanks to one of my colleagues who pushed me in this direction. Kubernetes gives you yet another tool to handle Secrets in environment variables. This time, it is more convenient since you only point it to the complete Secret, not just a single value. Kubernetes will then make all key-value pairs available as individual environment variables.

Read More »

Simplify Spring Boot Access to Secrets Using Spring Cloud Kubernetes

This topic has its origin in how we manage Kubernetes Secrets at my workplace. We use Helm for deployments, and we must support several environments with their connection strings, passwords, and other settings. As a result, some things are a bit more complicated, and one of them is the access to Kubernetes Secrets from a Spring Boot application running in a Pod.

This blog post covers the following:

  1. How do you generally get Secrets into a Pod?
  2. How do we currently do it using Helm?
  3. How can it be improved with less configuration?
  4. Any gotchas? Of course, it is software.

I will explain a lot of rationales, so expect a substantial amount of prose between the (code) snippets.

Read More »

Apache Commons CLI Handling of –help

An odd thing about Commons CLI is that it has no built-in concept of a “–help” option. Other libraries, like JCommander do (which had other problems, or I would not have bothered with Commons CLI). As a result, you have to build it on your own. It is not enough to include it with all the other application options, especially if you use required arguments. Then it is impossible to only set the Help option.

You must implement a two-step process. See this demo application on GitHub that I created for another blog post. It shows this in action.

First, only parse for the Help option, and if it is present, print the help text and exit the application. To print the complete help text, you must add the other parameters first, though. Otherwise there would be only “–help”.

final var applicationOptions = example_2_Options();

final var options = example_2_Help();
final var cli = parser.parse(options, args, true);

if (cli.hasOption(help)) {
    // Append the actual options for printing to the command-line.
    applicationOptions.getOptions().forEach(options::addOption);
    new HelpFormatter().printHelp("external-config-commons-cli", options);
    return;
}

Second, if no help is requested, parse for the application options.

final var cli = parser.parse(applicationOptions, args, true);

applicationOptions.getOptions().forEach(opt -> {
    if (cli.hasOption(opt)) {
        System.out.printf("Found option %s with value %s%n",
                opt.getOpt(), cli.getOptionValue(opt));
    }
});

Thank you very much for reading. I hope this was helpful.

Spring Boot Externalized Config on Command Line With Apache Commons CLI – Missing Required Option

I know this title is a bit of a mouthful, but you need to get all the keywords in for Google to do its magic 😉. In the previous blog post, I mentioned that I would take another look at this topic through the lens of a programmer that uses Apache Commons CLI for command-line argument handling. In a project for work, I noticed some odd error messages claiming that a command-line option did not have a value assigned to it, although it obviously did.

A more extensive set of examples can be found in the README file on GitHub, together with the code.

The sole reason for this blog post is how unknown parameters from the view of Commons CLI can mess up the parsing. The demo application defines two required Options – one for input (“-i” or “–input”) and one for output (“-o” or “–output”). Consider this command where I also set a Spring configuration setting.

% java -jar target/external-config-commons-cli-1.0.0.jar --spring.config.additional-location=src/config/application-mac.yml -i in -o out
-> AppRunner.run() Command Line Arguments
Argument: --spring.config.additional-location=src/config/application-mac.yml
Argument: -i
Argument: in
Argument: -o
Argument: out
-> ExternalConfigProperties
Input path: /Users/mac/thecode
Output path: /Users/mac/slinger
-> Parsing Help With Apache Commons CLI
-> Parsing Arguments With Apache Commons CLI
Missing required options: i, o

Both options are clearly there. The raw output of the String… args array shows that. By default, Commons CLI complains about unknown options. I disabled that behavior by setting stopAtNonOption to true. The parameter’s name makes no sense to me because it does not stop, but I might misinterpret something.

Either way, I assume that Commons CLI expects an option and a value by default. –spring.config.additional-location=src/config/application-mac.yml is a continuous string, an option without a value – at least to Commons CLI. Then it reads -i as the value to that option, and from there, the parsing goes south. The actual options are interpreted as values now.

Note, though, that Spring still accepts the configuration setting.

How can we fix that? There are two ways to do that:

  1. Add the Spring arguments at the end of the command line.
  2. Use the JVM-style Spring arguments with “-D”, as alluded to in the other blog post.

Putting the argument at the end:

% java -jar target/external-config-commons-cli-1.0.0.jar -i in -o out --spring.config.additional-location=src/config/application-mac.yml
-> AppRunner.run() Command Line Arguments
Argument: -i
Argument: in
Argument: -o
Argument: out
Argument: --spring.config.additional-location=src/config/application-mac.yml
-> ExternalConfigProperties
Input path: /Users/mac/thecode
Output path: /Users/mac/slinger
-> Parsing Help With Apache Commons CLI
-> Parsing Arguments With Apache Commons CLI
Found option i with value in
Found option o with value out

Using the JVM-style:

% java -Dspring.config.additional-location=src/config/application-mac.yml -jar target/external-config-commons-cli-1.0.0.jar -i in -o out
-> AppRunner.run() Command Line Arguments
Argument: -i
Argument: in
Argument: -o
Argument: out
-> ExternalConfigProperties
Input path: /Users/mac/thecode
Output path: /Users/mac/slinger
-> Parsing Help With Apache Commons CLI
-> Parsing Arguments With Apache Commons CLI
Found option i with value in
Found option o with value out

Thank you very much for reading. I hope this was helpful.

Spring Boot Externalized Config on Command Line

Spring Boot applications do not always have to serve as a web service located on the Internet. You can also use Spring Boot (or Spring without the Boot) for a command-line utility. I was recently faced with this task, and one requirement for the tool was to support setting a profile-specific configuration on the command line. This isn’t earth-shattering per se since that is a regular Spring feature. The goal was to provide a profile-specific configuration file on the command line that is not bundled in the application.

Imagine developing a Cloud service and running different environments for the different phases of your project – one for development tests, a staging environment, and, finally, the production environment. Connecting to the different environments may require secrets you do not want to be bundled in the application – and, thus, the source tree.

Now, you could roll your own configuration file reader. But wouldn’t it be nice to make full support of Spring’s @Value annotation or @ConfigurationProperties classes?

Read More »

My Year in Video Gaming 2021

2021 has been a challenging year, for obvious reasons, but also in other personal aspects that are not part of this little essay. Despite all the trials and tribulations, I have probably never played so many games in just one year – some of them in Coop and others all on my lonesome. Many of them I finished, others I, or we, aborted. But not only that, I have also managed to transition from PC gaming to console gaming – a long-held goal of mine.

As always, I am pretty late to the party because I have trouble motivating myself to write stuff, despite having the ideas and mentally developing concepts for them. Much thinking, few doing. One of my 2021 issues.

(I am surprised I managed to get this huge Halo Infinite review out the door.)Here is how this will go. I am starting with a story about why I replaced my gaming PC with consoles and a laptop. Then I transition into my experience with said consoles, and I conclude this gaming year review with the list of games I have played in lonely-mode or Coop. Don’t worry. I didn’t go Halo Infinite on every game. I kept it short-ish because the list is astonishingly long.

Read More »

Halo Infinite Review

When you look back at the history of video-based media, how many games or movies come to your mind with such an iconic theme song that it always evokes a particular feeling whenever you hear it? A theme that you immediately recognize and that conjures specific scenes or gameplay moments you are so fond of? Off the top of my head, I can think of two: The Imperial March from Star Wars and Halo’s invigorating battle soundtrack. Halo is back, infinitely better than Halo 5, and along with it, its recognizable music. I suggest you set the perfect mood and open the link above, and then come back and read my review of Halo Infinite. Start from the beginning because I linked directly to the battle music part (but that is also a good choice).

Now, is it even worth getting in the mood? If you ask yourself, I hope you do not mean my writing 😉. I hope you ask that question because you are anxious for a good game but afraid you might get disappointed. When I read and watched many reviews from known media outlets, I found very different opinions and wasn’t sure what to think. IGN mainly had positive things to say and was very upbeat in their Halo Infinite podcast episode. In contrast, the Germany-based Golem.de website found rather harsh words for some parts, mainly storytelling and the new AI (more on that later). The most common denominator among all of them was the excellent feeling combat. Looking at the complete experience, I think I land somewhere in the middle between Great and Mediocre, and if you are still curious, I will tell you why.

Read More »