REST != REST

Standards and best practices

REST is a defacto standard and every developer implements REST APIs in a different way.

In this talk I’ll show best practices and standards around REST. I talk about developer experience with REST APIs, resource naming conventions, URI structure, HTTP methods / status codes and the REST Maturity Model. And the end I cover HATEOAS and the JSON API.

Here are the slides:

I hope that helps you to build REST APIs with higher developer experience.

Test your code not throwing any exception

with JUnit and Assertj

Recently I had to test that the code does not throw any exception. We all know that AssertJ gives us a powerful set of assertions which improves your test code readability.

And again, AssertJ helped me to do the job with assertThatCode:

    Service service = new Service();
    assertThatCode(
        () -> {
          service.method();
        })
    .doesNotThrowAnyException();

You can find more assertions example on github.

I hope you learned a little something 🙂

Links

Github project https://github.com/claudioaltamura/java-assertj

AssertJ https://assertj.github.io/doc/

Id Software – Programming Principles

Produce constantly shippable codebase

I had the chance to see John Romero at a conference. He talked about the Id Software programming principles. They defined these rules through experience. Each is built upon one another, so it’s a unique methodology and which helps you to produce constantly shippable codebase.

You know these rules, but I was so impressed by these principles that I have written down them. I am not in the Gaming industry nor they are not new, but as a whole, I think they are really the recipe to produce constantly high-quality shippable software.

Here are the slides:

Spring Actuator Metrics availableTags

Get useful metrics to monitor your app

With Spring Actuator API several useful metrics can be exposed that you can use to monitor your Spring Boot application. Metrics like application health or the last HTTP requests. I’ll show you how to do that.

I’ve made an example project you can found at https://github.com/claudioaltamura/docker-springboot-helloworld. After starting the app, you can curl the metrics with

curl -i -X GET http://localhost:8080/actuator/metrics

While consuming the API, you may notice the property „availableTags“, for example if you query the „jvm.memory.max“ metric:

curl -X GET 'http://localhost:8080/actuator/metrics/jvm.memory.max' | jq . 
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   382    0   382    0     0  64169      0 --:--:-- --:--:-- --:--:-- 76400
{
  "name": "jvm.memory.max",
  "description": "The maximum amount of memory in bytes that can be used for memory management",
  "baseUnit": "bytes",
  "measurements": [
    {
      "statistic": "VALUE",
      "value": 5446303743
    }
  ],
  "availableTags": [
    {
      "tag": "area",
      "values": [
        "heap",
        "nonheap"
      ]
    },
    {
      "tag": "id",
      "values": [
        "Compressed Class Space",
        "PS Survivor Space",
        "PS Old Gen",
        "Metaspace",
        "PS Eden Space",
        "Code Cache"
      ]
    }
  ]
}

If you are interested in a specific metric, e.g. Comprossed Class Space than you can query only this metric like this:

curl -X GET 'http://localhost:8080/actuator/metrics/jvm.memory.max?tag=area%3Anonheap&tag=id%3ACompressed+Class+Space' | jq .
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   217    0   217    0     0  47132      0 --:--:-- --:--:-- --:--:-- 54250
{
  "name": "jvm.memory.max",
  "description": "The maximum amount of memory in bytes that can be used for memory management",
  "baseUnit": "bytes",
  "measurements": [
    {
      "statistic": "VALUE",
      "value": 1073741824
    }
  ],
  "availableTags": []
}

HTH 🙂

Links
Github Example https://github.com/claudioaltamura/docker-springboot-helloworld
Spring Boot Documentation https://docs.spring.io/spring-boot/docs/2.0.0.BUILD-SNAPSHOT/actuator-api//html/#metrics-drilling-down

Format code like google

Get easy look-alike readable code with IntelliJ

Spotless is are really cool tool for formatting your code with build tools. If you like, you can do that with your IDE too. I show your how to configure IntelliJ, so your code is automatically formatted while you save a file.

First you have to install the Google Java Format Plugin. After that please install the Save Action Plugin. Now go to File→Settings→Other Settings→Save Action and activate „Activate save action on save“. Activate the Formating Actions „Optimize imports“ and „Reformate File“ too.

Check the google-java-format setting, if the plugin is enabled. Unfortunately the import ordering is not handled by this plugin. To fix the import order, download the IntelliJ Java Google Style file and import it into File→Settings→Editor→Code Style.

That’s it. Happy coding.

Links
Spotless Gradle Plugin https://github.com/diffplug/spotless/tree/master/plugin-gradle
IntelliJ Google Java Format Plugin https://plugins.jetbrains.com/plugin/8527-google-java-format
IntelliJ Save Action Plugin https://plugins.jetbrains.com/plugin/7642-save-actions
IntelliJ Java Google Style file https://raw.githubusercontent.com/google/styleguide/gh-pages/intellij-java-google-style.xml

Discover updates or vulnerabilities

Keep your dependencies up-to-date with gradle

This is an import task, e.g. nearly every 6 months major releases of frameworks are available or new vulnerabilities are found on a daily basis.

I’ll show you two gradle plugins which helps you that your software project won’t be left behind. The first one is gradle-version-plugin. This plugin discovers dependency updates. Just add this to your build.gradle:

plugins {
  id "com.github.ben-manes.versions" version "0.21.0"
}

With the task dependencyUpdates you get a simple text report of the project dependencies that are up-to-date or have upgrades.

./gradlew dependencyUpdates -Drevision=release

You can find the report in {projectDir}/build/dependencyUpdates/report.txt

------------------------------------------------------------
: Project Dependency Updates (report to plain text file)
------------------------------------------------------------

The following dependencies are using the latest release version:
 - com.github.ben-manes.caffeine:caffeine:2.7.0
...
The following dependencies have later release versions:
 - com.google.guava:guava [25.1-jre -> 28.0-jre]
     https://github.com/google/guava
...

The second plugin is dependency-check-gradle which helps you to monitor dependent libraries for known, published vulnerabilities.

plugins {
  id "org.owasp.dependencycheck" version "5.0.0"
}

dependencyCheckAnalyze generates a report in build/reports/dependency-check-report.html

./gradlew dependencyCheckAnalyze --info

In the report every dependency is listed with severity, cve count, confidence and evidence count.

Solid dependency management is a primary requirement. Dependency updates should be a regular step in your software development cycle.

Links
gradle-version-plugin
dependency-check-gradle

Never write in Java a getter or equals method again

The lombok project helps you to be more productive

Lombok is a great tool. Your code often gets verbose for common tasks. So what does lombok? The framework is plugged into the build process. It autogenerates bytecode into your class fields through a couple of annotations.

Here comes the build.gradle:

dependencies {
  compileOnly 'org.projectlombok:lombok:1.18.8'
  annotationProcessor 'org.projectlombok:lombok:1.18.8'

  testImplementation 'org.junit.jupiter:junit-jupiter-api:5.4.2'
  testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.4.2'
}

So let’s have a look at the lombok annotations

package de.claudioaltamura.java.lombok;

import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;

@NoArgsConstructor
@AllArgsConstructor
@Getter 
@Setter
@EqualsAndHashCode
@ToString
public class SuperHero {

  private String name;

  private String city;

}

I put all annotations on class level. I added to constructor annotations here: first @NoArgsConstructor. This annotation adds a constructor with no arguments. And the second annotation is @AllArgsConstructor, which generates a constructor with every field.

With @Gettter and @Setter lombok generates default getter and setter for your class. And of course @EqualsAndHashCode and @ToString annotations are very nice too.

These are only a few examples which features lombok provides. Have a look a the project for more informations.

The example project is on github :-).

Trace http requests with Spring Actuator

List the last http request with ease

Spring Actuator provides also a httptrace endpoint. You get the last HTTP request with /httptrace.

After adding Spring Boot Actuator dependencies to your project dependencies, you have to expose the httptrace endpoint via your application.properties:

[code]management.endpoints.web.exposure.include=httptrace[/code]

[code] curl http://127.0.0.1:8080/actuator/httptrace | jq { "traces": [{ "timestamp": "2019-01-05T07:45:14.406Z", "principal": null, "session": null, "request": { "method": "GET", "uri": "http://127.0.0.1:8080/helloworld/peter", "headers": { "host": ["127.0.0.1:8080"], "accept": ["*/*"], "user-agent": ["curl/7.58.0"] }, "remoteAddress": null }, "response": { "status": 200, "headers": { "Content-Length": ["16"], "Date": ["Sat, 05 Jan 2019 07:45:14 GMT"], "Content-Type": ["text/plain;charset=UTF-8"] } }, "timeTaken": 7 }] } [/code]

In Spring Boot 2.0 the trace endpoint was renamed to httptrace. You can even configure the trace details (see TraceProperties.java code).
Here is an example

[code]management.httptrace.include = parameter[/code]


Here is the source code of my sample application 🙂

Links

List of Spring Actuator endpoints
List of Spring application properties

Change your application log level with Spring Actuator

You can do it even at runtime 🙂

Spring Boot provides a loggers actuator endpoint for viewing and changing log levels at runtime. What do I need?

Add the Spring Boot Starter Actuator to you pom.xml or build.gradle
org.springframework.boot:spring-boot-starter-actuator

Expose at least the loggers endpoint in your application.properties
management.endpoints.web.exposure.include=loggers

When exposed, you get all loggers details with /loggers:

[code]
curl http://127.0.0.1:8080/actuator/loggers | jq

{
"levels": ["OFF", "ERROR", "WARN", "INFO", "DEBUG", "TRACE"],
"loggers": {
"ROOT": {"configuredLevel": "INFO", "effectiveLevel": "INFO" },
"de": {"configuredLevel": null, "effectiveLevel": "INFO" },
"de.claudioaltamura": {"configuredLevel": null, "effectiveLevel": "INFO"}
}
}
[/code]

For changing a specific logger level at runtime, execute a POST request:

[code]
curl -i -X POST -H ‚Content-Type: application/json‘ -d ‚{"configuredLevel": "DEBUG"}‘ "http://localhost:8080/actuator/loggers/de.claudioaltamura"

HTTP/1.1 204
[/code]

Try it out, here is my github project for this article.

Creating a generic array in Java

Generic array initialization

Recently I work with CompletableFutures. I used the allOf method which
takes a varargs as input. Based on the request, a couple of things had to be processed.

So how do I create a generic array that I could use at CompletableFuture.allof()?
Array.newInstance together with toArray() does the trick.

This is my solution:

https://gist.github.com/claudioaltamura/dac3f56e41a77a052c59539cc06fb52e

Consent Management Platform von Real Cookie Banner