Qt5 QtCreator Error on Linux: stddef.h: No such file or directory – Code model could not parse an included file

The following is an error that has shown itself every time I have installed the Qt5 framework and the QtCreator development environment on a Linux based machine. It never mattered which flavor of Linux; QtCreator always showed this error.

Warning: The code model could not parse an included file, which might lead to incorrect code completion and highlighting, for example. 

fatal error: 'stddef.h' file not found 
note: in file included from /home/rlo/Code/C++/WorkTracker2/WorkTracker2Shared/src/data/taskrepository.h:1: 
note: in file included from /home/rlo/Code/C++/WorkTracker2/WorkTracker2Shared/src/data/taskrepository.h:3: 
note: in file included from /usr/include/c++/9/optional:38: 
note: in file included from /usr/include/c++/9/stdexcept:38: 
note: in file included from /usr/include/c++/9/exception:143: 
note: in file included from /usr/include/c++/9/bits/exception_ptr.h:38: 

Although that message never caused any issues compiling the code, I found it rather annoying, and at some point, annoying enough to search for a solution.

As it turns out, this message appears when you have Clang libraries installed. QtCreator detects that and automatically uses Clang to parse the source code and provide inline error messages and code completion.

You can get rid of this error when you explicitly add the STL header files’ include-path to your project. In my case, I have added the following to my *.pro file.

unix {
    INCLUDEPATH += /usr/lib/gcc/x86_64-linux-gnu/9/include
}

Azure PostgreSQL Error: PSQLException The connection attempt failed

A few days ago at work, I was investigating a strange issue where one of our services could not connect to the Azure Managed PostgreSQL Database from the Kubernetes cluster. Oddly enough, other services of that cluster did not exhibit this behavior.

org.postgresql.util.PSQLException: The connection attempt failed.
        at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:315) ~[postgresql-42.2.16.jar!/:42.2.16]
        at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:51) ~[postgresql-42.2.16.jar!/:42.2.16]
        at org.postgresql.jdbc.PgConnection.<init>(PgConnection.java:225) ~[postgresql-42.2.16.jar!/:42.2.16]
        at org.postgresql.Driver.makeConnection(Driver.java:465) ~[postgresql-42.2.16.jar!/:42.2.16]
        at org.postgresql.Driver.connect(Driver.java:264) ~[postgresql-42.2.16.jar!/:42.2.16]
        ...
        at org.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:49) ~[ehg-hermes.jar:0.13.0-SNAPSHOT]
        at org.springframework.boot.loader.Launcher.launch(Launcher.java:107) ~[ehg-hermes.jar:0.13.0-SNAPSHOT]
        at org.springframework.boot.loader.Launcher.launch(Launcher.java:58) ~[ehg-hermes.jar:0.13.0-SNAPSHOT]
        at org.springframework.boot.loader.JarLauncher.main(JarLauncher.java:88) ~[ehg-hermes.jar:0.13.0-SNAPSHOT]
Caused by: java.io.EOFException: null
        at org.postgresql.core.PGStream.receiveChar(PGStream.java:443) ~[postgresql-42.2.16.jar!/:42.2.16]
        at org.postgresql.core.v3.ConnectionFactoryImpl.enableGSSEncrypted(ConnectionFactoryImpl.java:436) ~[postgresql-42.2.16.jar!/:42.2.16]
        at org.postgresql.core.v3.ConnectionFactoryImpl.tryConnect(ConnectionFactoryImpl.java:144) ~[postgresql-42.2.16.jar!/:42.2.16]
        at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:213) ~[postgresql-42.2.16.jar!/:42.2.16]
        ... 46 common frames omitted

As it turns out, it was an issue with the PSQL JDBC driver version that comes bundled with Spring Boot version 2.3.4-RELEASE. All the other services were still built with a slightly older release and therefore used an older PSQL JDBC driver.

The key indicator of what is going on is this method call.

org.postgresql.core.v3.ConnectionFactoryImpl.enableGSSEncrypted

A bit of research led me to a question on StackOverflow that pointed me in the right direction, and ultimately I ended up on Microsoft’s Azure documentation. If you scroll down, you will find a section named "GSS error".

The solution to this problem is simple. If you do not want or cannot change the Spring Boot or PSQL JDBC driver version, e.g., because of automated CVE scans that break builds (the reason we upgraded this one service), then you can solve it with a configuration change. Append gssEncMode=disable to the JDBC connection string.

Example: jdbc:postgresql://svc-pdb-name.postgres.database.azure.com:5432/databasename?gssEncMode=disable

CMake on Windows 10 with Qt5 Error: CMAKE_PREFIX_PATH

Quick one: Set the proper CMAKE_PREFIX_PATH value for Qt5 development on Windows 10 with MinGW and CMake.

Here is the lovely error you get from CMake.

CMake Error at CMakeLists.txt:13 (find_package):
 By not providing "FindQt5.cmake" in CMAKE_MODULE_PATH this project 
has
 asked CMake to find a package configuration file provided by "Qt5", 
but
 CMake did not find one.

 Could not find a package configuration file provided by "Qt5" with 
any of
 the following names:

 Qt5Config.cmake
 qt5-config.cmake

 Add the installation prefix of "Qt5" to CMAKE_PREFIX_PATH or set 
"Qt5_DIR"
 to a directory containing one of the above files. If "Qt5" provides a
 separate development package or SDK, be sure it has been installed.

CMake asks you to tell it where to find the Qt5 *.cmake configuration files. One option is to set the CMAKE_PREFIX_PATH variable. The Qt5 documentation has the following to say about that:

The easiest way to use CMake is to set the CMAKE_PREFIX_PATH environment variable to the install prefix of Qt 5.

Now, what the hell is the "install prefix"? It turns out it is the path where you can find the compiler-specific Qt binaries, include files and the other stuff. In my case, using MinGW, it is located at "C:\Apps\Qt\5.14.2\mingw73_64". If you are using the MSVC binaries, select the corresponding directory, probably something like "C:\Apps\Qt\5.14.2\msvc_2017".

Maven Failsafe Plugin environmentVariables Not Working (org.postgresql.Driver claims to not accept jdbcUrl)

A few months ago I had written about how one can setup a PostgreSQL database in a docker container during the Maven testing phase (part 1 and part 2). Today, I wanted to iterate on this topic using Testcontainers. Unfortunately, before I could get to that I ran into issues with the original project. For some reason I was now getting the following error:

Caused by: java.lang.RuntimeException: Driver org.postgresql.Driver claims to not accept jdbcUrl, jdbc:postgresql://localhost:${it-database.port}/docker_db_testing_tests

Maven did not replace the variable it-database in the integration test application.properties file. The question is: "why now"? It has worked before. Now, one thing that I changed is that this time I was using Linux instead of Windows. Either way, the fix was simple, although not obvious. It seems to be an issue with the Maven Failsafe plugin.

Not working:

<configuration>
    <environmentVariables>
        <it-database.port>${it-database.port}</it-database.port>
    </environmentVariables>
</configuration>

Working:

<configuration>
    <systemPropertyVariables>
        <it-database.port>${it-database.port}</it-database.port>
    </systemPropertyVariables>
</configuration>

Here is the link to the commit.

Spring Multipart File – Can I Read InputStream Multiple Times?

The short answer is Yes.

Here is the long version and why I even asked myself this question.

If you are familiar with ServletRequest then you probably know that calling its getInputStream method only works once. If you need to read the body data multiple times then it is up to you to cache it in a buffer or employ workarounds such as a "caching servlet request". Unfortunately, this fact is not stated in the Javadoc of ServletRequest#getInputStream so it is no wonder this question gets asked.

Spring’s MultipartFile is a bit different here. It, too, has a getInputStream method, but this one can be called multiple times. Again, it is not obvious from the documentation which is why I am making this mental note for myself and others who are researching this question because they know about the behavior of ServletRequest and assume – as I did – it is the same for MultipartFile. Fortunately, it is not.

In my case I needed to compute a hash of an uploaded file and then move the file to Azure’s Blob Storage. The Azure API used an InputStream and I assumed, once I had consumed the multipart InputStream that I could not use that API anymore.

As a side note: Using DigestInputStream it is possible to do this in one go, move the data to storage and while doing that compute the hash. In my case, I needed the hash first to compare it with a value that was provided on upload. Only when they match can the data be transferred to storage.

Automate Game Screenshot Capture: Windows API SendInput Function with C++

I am trying to write video game reviews after I have finished a game and I like to add some impressions in the form of screenshots to the reviews. There is one problem though: sometimes it is impossible to press the keyboard shortcut to capture a screenshot because the game requires my full attention – and all my fingers. Therefore, I miss out on a lot of action sequences. What does a programmer do in such a situation? Write a tool that scratches the itch.

Read More »

Mockito “when” vs. “verify”

Recently, during a code review at work there was a discussion about whether Mockito’s verify is necessary when when (or given, which is a synonym) is parameterized. The quick answer is "no".

Imagine this contrived example. I have two classes, Calculator and ComplexOperationService, where the latter requires the former. The goal is to write a unit test for ComplexOperationService and mock all usages of Calculator.

Here are the two classes.

public class Calculator {

    public int sum(final int a, final int b) {
        return a + b;
    }
}

@RequiredArgsConstructor
public class ComplexOperationService {
    
    private final Calculator calculator;

    public void doComplexOperation(final int a, final int b) {
        System.out.println(calculator.sum(a, b));
    }
}
Read More »

Integration Testing with Docker Maven Plugin, PostgreSQL, Flyway (Update)

Recently I have written about how one can create a PostgreSQL Docker image with the Docker Maven Plugin to run integration tests that require a database. While this worked all nice and well during development, the concept has one flaw: the plugin will push the database Docker image to a Docker registry during the deploy phase. I do not want this temporary image to end up there. This is the behavior of the Docker Maven Plugin and I have not found a way to work around this. By “work around this” I mean somehow configure the plugin to ignore this custom PSQL image during the “deploy” phase. Unfortunately, there is only a global <filter> that applies to all the phases of the plugin.

There is a proper solution however, at least for what I was using the database.

Read More »

Windows Subsystem for Linux (WSL) Docker: error storing credentials – err: exit status 1, out: Cannot autolaunch D-Bus without X11 $DISPLAY

Recently at work, when copying an application from our internal Docker Registry to Azure, I ran into the following error in my WSL Ubuntu installation.

Login at docker..com
Username: 
Password:
Error saving credentials: error storing credentials - err: exit status 1, out: `Cannot autolaunch D-Bus without X11 $DISPLAY`
ERROR: source registry login failed

The easiest fix I found was to install the gnupg2 and pass packages.

sudo apt install gnupg2 pass 

One important thing to note regarding security: the output mentioned storing the credentials in plain text as a result somewhere in the WSL user’s /home directory. If you are very conscious about where passwords are stored, do not use this solution or remove the password file afterwards. That’s good enough for me at the moment, I just needed to get this to work somehow.

Integration Testing With Docker Maven Plugin, PostgreSQL, Flyway

Some things in software development require more than mocks and unit testing. If your application uses a database it makes sense to also hit that database in automated testing to ensure custom SQL queries work correctly, Hibernate relations are set up properly and also that database migrations are successful.

This blog post was written with a focus on the latter. I will be using Spring Boot talking to a PostgreSQL database. The database structure is managed via Flyway and, basically customary for Java applications, Maven serves as the build and dependency management tool. Docker will also play a role because we’ll be creating and running a PostgreSQL docker image for testing. From Maven. Every time the test is executed. And to spice things up, we’ll also create a custom database and user in that dockerized PSQL image.

I have created a working sample on Github and you can follow every single step by taking a look at the commit history. There you can see individual changes, starting from an empty Spring Boot application with no database to the final solution with Spring Data JPA and Flyway.

In the following sections and snippets, I will highlight the important parts of each step.

Read More »

Comparing Java Optional vs C++ STL optional

Optionals in Java have been around for some time now, basically since the release of version 8. My other language of choice, C++, has received this feature in version C++17. Since I am currently in the process of writing some C++ code, I was curious how they were implemented there. Optionals are trying to solve a problem that is likely to plague any language. What shall a method or function return if there is no value? Or shall it not return anything but instead start crying like a petulant child and throw an exception?

As an introduction, let me dive a little bit into why we need optionals (or do we?) and compare two different implementations of this concept, one being java.util.Optional and the other C++ std::optional. I chose to compare these two language for several reasons:

  1. I work with Java in my day job, so I have a good idea of how it works there.
  2. As mentioned, C++ is one of the languages I know quite well too.
  3. The main reason: both optional implementations are add-on classes rather than language features. More on that later.
Read More »

Spring @ConfigurationProperty a Bean or not?

Semi-recently (“semi” because procrastination kept me from writing, so it’s more like two months ago, but blog posts have to start with “recently” when you try to explain yourself why you are writing what you are writing – but I’m getting sidetracked here, so let’s move on) I was wondering whether Java classes annotated with Spring’s @ConfigurationProperty should be declared as a bean, e.g. with @Component. I didn’t find a definitive answer, but I found three ways on how to do it – typical Spring, I guess.

Here’s a quick setup:

My configuration class.

package com.thecodeslinger.configpropsdemo;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties; 

@Data 
@ConfigurationProperties(prefix = "demo")
public class Configuration {

    private String elegy;
}

My main application:

package com.thecodeslinger.configpropsdemo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import javax.annotation.PostConstruct;

@SpringBootApplication
public class ConfigPropsDemoApplication {

   @Autowired
   private Configuration configuration;

   @PostConstruct
   public void postConstruct() {
      System.out.println(configuration.getElegy());
   }

   public static void main(String[] args) {
      SpringApplication.run(ConfigPropsDemoApplication.class, args);
   }
}

And finally, my properties file:

demo.elegy=R.I.P. Kobe

It’s not an elegant setup, but that’s not the point. It does the job for now.

If you run the application in this state, Spring will greet you with an error message.

APPLICATION FAILED TO START

Description:
Field configuration in com.thecodeslinger.configpropsdemo.ConfigPropsDemoApplication required a bean of type 'com.thecodeslinger.configpropsdemo.Configuration' that could not be found.
The injection point has the following annotations:
- @org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'com.thecodeslinger.configpropsdemo.Configuration' in your configuration.

It obviously cannot find the configuration bean.

Option #1: Slap @Component to it.

package com.thecodeslinger.configpropsdemo;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Data
@Component
@ConfigurationProperties(prefix = "demo")
public class Configuration {

    private String elegy;
}

Option #2: Use the @EnableConfigurationProperties annotation.

import org.springframework.boot.context.properties.EnableConfigurationProperties;

@SpringBootApplication
@EnableConfigurationProperties(Configuration.class)
public class ConfigPropsDemoApplication {

Option #3: Use @ConfigurationPropertiesScan to explicitly name the packages to scan for.

import org.springframework.boot.context.properties.ConfigurationPropertiesScan;

@SpringBootApplication
@ConfigurationPropertiesScan({"com.thecodeslinger.configpropsdemo"})
public class ConfigPropsDemoApplication {

All three options achieve what you’re aiming for, a running application.

:: Spring Boot :: (v2.2.4.RELEASE)
2020-02-03 19:57:43.562 INFO 4612 --- [ main] c.t.c.ConfigPropsDemoApplication : Starting ConfigPropsDemoApplication on DESKTOP-C0O3OKC with PID 4612 (D:\OneDrive\Code\Java\config-props-demo\target\classes started by lober in D:\OneDrive\Code\Java\config-props-demo)
2020-02-03 19:57:43.562 INFO 4612 --- [ main] c.t.c.ConfigPropsDemoApplication : No active profile set, falling back to default profiles: default
R.I.P. Kobe
2020-02-03 19:57:43.921 INFO 4612 --- [ main] c.t.c.ConfigPropsDemoApplication : Started ConfigPropsDemoApplication in 0.573 seconds (JVM running for 1.083)

So, is there any benefit of one over the other? The Spring documentation has the following to say:

Sometimes, classes annotated with @ConfigurationProperties might not be suitable for scanning, for example, if you’re developing your own auto-configuration or you want to enable them conditionally. In these cases, specify the list of types to process using the @EnableConfigurationProperties annotation. This can be done on any @Configuration class, as shown in the following example:

I’m not using a @Configuration class in my example, but if you were, you could leverage that to load your configuration classes based on @Profile annotations. Although @Component works too, it’s not mentioned in that part of the Spring documentation (“Type-safe Configuration Properties”).

For myself, I might go with @EnableConfigurationProperties and if it makes sense, even have dedicated @Configuration classes linked to @Profile. For little samples like this one it’s obviously overkill. In a remotely useful application, the additional overhead may be worth it for structural and documentational reasons.

Kotlin Object Expression – What more can object do?

In a previous post I explained what Kotlin Object Declarations are. This time around it’s about the declaration’s sibling, the Object Expression.

An object is not just a glorified static replacement or a singleton. object can be used where Java usually utilizes anonymous inner classes. Let’s look at a more realistic scenario: a JButton and an ActionListener or a MouseListener.

Read More »

Kotlin Object Declarations – The fake-static

Instead of implementing my own backup application as I had planned a long time ago, I’m wandering off (re)learning Kotlin after a long absence from that language. In my defense though, I’m doing it in the context of the backup app which will not be Java as originally intended (or maybe later for comparison, who knows, I obviously can’t be trusted with my plans). Putting that aside, the most confusing concept of Kotlin for a Java developer is the object. What is that thing doing that a class can’t do and how do we declare static fields and methods? I know it’s nothing new, but that part seems to have changed a bit since I used Kotlin about two (?) years ago. So, for me this is a refresh of old information and also something new and by writing about it I will engrave it in my brain once and for all. And your confusion will hopefully turn into some productive… fusion… of some sort… or so.

Read More »

Unwanted JUnit 4 Dependency with Kotlin and JUnit 5

I ran across this issue only by accident because I was investigating a completely different problem. I wrote a quick test to debug my issue and was wondering why custom serializers and deserializers are not registered with the Jackson ObjectMapper. I had a nice init() function that was annotated with @Before. So, what the hell?

Let’s back up a bit for some context.

  • Kotlin Project
  • Runs on Java 12
  • JUnit 5 as test engine
  • AssertK for assertions (just for the sake of completeness)

I’m used to JUnit 4, so in my test I used @Before to annotate a setup method. It was one of the many options IntelliJ presented to me.

@Before
fun init() {
    val module = SimpleModule()
    module.addDeserializer(Instant::class.java, InstantDeserializer())
    module.addSerializer(Instant::class.java, InstantSerializer())
    mapper.registerModule(module)
}

The method wasn’t called, however. But it’s annotated! Well, it’s the wrong annotation if you’re using JUnit 5. The correct one is @BeforeEach. This one and @BeforeClass (new name @BeforeAll) have been changed from version 4 to 5 to make their meaning more obvious.

But that’s besides the point. The question is: where does this @Before come from then?

A look at the dependency tree quickly reveals the culprit.

It’s the official JetBrains Kotlin JUnit test artifact. Although it doesn’t hurt me to have it in my project, it certainly caused some confusion and I’d like to avoid that in the future. Hence, I excluded the old version of JUnit in my POM file for this dependency.

<dependency>
    <groupId>org.jetbrains.kotlin</groupId>
    <artifactId>kotlin-test-junit</artifactId>
    <version>${kotlin.version}</version>
    <scope>test</scope>
    <exclusions>
        <exclusion>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
        </exclusion>
    </exclusions>
</dependency>

Problem solved.