Categories
Development

GitHub Security

Dependabot

Habe gestern gehört, dass es auf GitHub einen Dienst gibt, der die Aktualität der verwendeten Bibliotheken überwacht und über neuere Versionen informiert.

Der Dienst heißt Dependabot

Auf GitHub gibt es einen Blog Eintrag dazu und GitHub-Dokumentation gibt es auch.

Dependabot einrichten

Im Projekt wird Maven verwendet und daher lautet das package-ecosystem laut Dokumentation überraschenderweise: "maven":

Pull request

Dass es funktioniert hat, konnte ich direkt daran sehen, dass ein Pull request angezeigt wird:

Merge & confirm pull request. Und schon ist die pom.xml wieder up to date. Das war ja einfach.

Dependabot security updates

Da die version updates so gut geklappt haben, aktiviere ich die security updates, für die auch die alerts aktiviert werden müssen:

Das Aktivieren hat keine Auswirkungen gezeigt, vermutlich ist mein Sample Projekt schon sicher.

Code scanning

Als Sprache wurde Java automatisch erkannt, daher kann die Konfigurationsdatei unverändert gespeichert werden.

Unter Actions kann ich sehen, dass der Code scanning workflow gelaufen ist und es Probleme gibt:

Logfiles suchen und herunterladen, da sie zu lang für den Webviewer sind.

Fatal error compiling: error: invalid target release: 17

Hier findet sich ein Hinweis: "Have you set up a Java 17 environment on Actions using https://github.com/actions/setup-java?"

Die Dokumentation hilft weiter und der Workflow wird um einen Schritt erweitert: Set up JDK 17

Docx4JSample/.github/workflows/codeql.yml
    - name: Set up JDK 17
      uses: actions/setup-java@v3
      with:
        java-version: '17'
        distribution: 'temurin'

Anschließend läuft der Job durch:

Der Erfolg des Scans findet sich im Security Tab unter Code scanning:

Secret scanning

Receive alerts on GitHub for detected secrets, keys, or other tokens.

https://github.com/DerIngo/Docx4JSample/settings/security_analysis

Klingt interessant. Mein Projekt hat keine Secrets, also füge ich erstmal eine Properties-Datei mit einem geheimen Passwort hinzu:

Anschließend wird das Secret scanning aktiviert:

Es wird kein Secret Alert ausgelöst:

Anschließend füge ich dem password auch noch ein username hinzu, aber das Ergebnis bleibt das Gleiche.

In der Dokumentation finden sich Supported secrets, ich probiere eines davon ("adafruit_io_key") als Property-Eintrag aus. aber das Ergebnis bleibt das Gleiche.

Ich suche nach "adafruit_io_key" und erweitere die Properties-Datei ein weiteres mal:

Aber das Ergebnis bleibt das Gleiche.

Ich probiere es mit einer weiteren Secret Datei:

Aber das Ergebnis bleibt das Gleiche.

Also sind meine Fake-Credentials zu billig, als dass GitHub darauf anspringt, oder das Feature funktioniert anders als gedacht.

Categories
Development Linux

Man In The Middle (ZScaler)

Version 2 aus dem Beispiel Reverse Proxy mit OneLogin soll zu Testzwecken in der Cloud zum Laufen gebracht werden.

Bei dem PoC handelt es sich um einen Apache HTTP-Server mit simpler Public Page und OneLogin Authentifizierung für den Zugriff auf die Private Page: der ShowHeaders Anwendung in einem Apache Tomcat-Server. Beide Server laufen in Docker Containern, die über Docker Compose gestartet werden.

Cloud Server einrichten

Auf dem Server muss Docker etc. eingerichtet werden:

sudo su

yum install docker -y
systemctl umask docker
systemctl start docker
docker version

curl -L https://github.com/docker/compose/releases/download/v2.2.3/docker-compose-`uname -s`-`uname -m` -o /usr/bin/docker-compose
chmod +x /usr/bin/docker-compose
docker-compose --version
# # Output:
# Docker Compose version v2.2.3

yum install git -y
mkdir /app
cd /app
git clone https://github.com/DerIngo/DockerOneLoginApacheSample.git

vim /app/DockerOneLoginApacheSample/version2/reverseproxy/conf/reverseproxy.conf

Fehler

Auf dem lokalen Entwicklerlaptop läuft der PoC und entsprechend soll er auch in der Cloud gestartet werden:

sudo su
cd /app/DockerOneLoginApacheSample/version2
docker-compose up

Zuerst sieht alles wie gewohnt aus, bis Maven ShowHeaders bauen soll:

root@showheaders:/usr/local/tomcat/ShowHeaders# mvn package
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------< deringo:ShowHeaders >-------------------------
[INFO] Building ShowHeaders 0.0.1-SNAPSHOT
[INFO] --------------------------------[ war ]---------------------------------
Downloading from central: https://repo.maven.apache.org/maven2/org/apache/tomcat/tomcat-catalina/8.5.53/tomcat-catalina-8.5.53.pom
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  0.956 s
[INFO] Finished at: 2022-06-07T12:28:46Z
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal on project ShowHeaders: Could not resolve dependencies for project deringo:ShowHeaders:war:0.0.1-SNAPSHOT: Failed to collect dependencies at org.apache.tomcat:tomcat-catalina:jar:8.5.53: Failed to read artifact descriptor for org.apache.tomcat:tomcat-catalina:jar:8.5.53: Could not transfer artifact org.apache.tomcat:tomcat-catalina:pom:8.5.53 from/to central (https://repo.maven.apache.org/maven2): Transfer failed for https://repo.maven.apache.org/maven2/org/apache/tomcat/tomcat-catalina/8.5.53/tomcat-catalina-8.5.53.pom: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/DependencyResolutionException

Es kann eine Dependency nicht aufgelöst werden und im Text findet sich dieser Satz: "PKIX path building failed". Also irgendwas mit Zertifikaten, wie mir die Erfahrung sagt.

Nach einer Recherche ist klar: In dem Cloud Setup wird der ausgehende Traffic durch einen Proxy geleitet und dessen Zertifikate sind nicht in den Standard-Zertifikaten enthalten.

Simple Lösung: Validierung aushebeln

Die schnellste Lösung: Einfach auf jedwede Validierung verzichten.

Aus Stackoverflow:

You can disable SSL certificate checking by adding one or more of these command line parameters:

  • -Dmaven.wagon.http.ssl.insecure=true - enable use of relaxed SSL check for user generated certificates.
  • -Dmaven.wagon.http.ssl.allowall=true - enable match of the server's X.509 certificate with hostname. If disabled, a browser like check will be used.
  • -Dmaven.wagon.http.ssl.ignore.validity.dates=true - ignore issues with certificate dates.

Official documentation: http://maven.apache.org/wagon/wagon-providers/wagon-http/

Here's the oneliner for an easy copy-and-paste:

-Dmaven.wagon.http.ssl.insecure=true -Dmaven.wagon.http.ssl.allowall=true -Dmaven.wagon.http.ssl.ignore.validity.dates=true

Umsetzung

In dem Dockerfile von ShowHeaders wird der Maven Aufruf um obige Parameter ergänzt:

WORKDIR ShowHeaders
# aus
    RUN mvn package
# wird
    RUN mvn package -Dmaven.wagon.http.ssl.insecure=true -Dmaven.wagon.http.ssl.allowall=true -Dmaven.wagon.http.ssl.ignore.validity.dates=true

und schon kann das Image wieder erfolgreich gebaut werden.

Der gleiche Fehler

Die Images werden gebaut, die Container starten und die Public Page wird korrekt angezeigt auf http://localhost:80/public

Aber: die Private Page auf http://localhost:80/private wird nicht angezeigt, bzw. wird nicht mal das OneLogin Login angezeigt.

Das Problem findet sich in der OpenID Konfiguration für OneLogin:

OIDCProviderMetadataURL https://deringo-dev.onelogin.com/oidc/2/.well-known/openid-configuration

Per HTTPS soll die Außenwelt erreicht werden, doch auch hier ist wieder der Proxy dazwischen.

Der Aufruf mittels http wird direkt auf https umgeleitet.

Die Validierung kann hier nicht so einfach ausgehebelt werden, falls überhaupt.

Lösung: Zertifikat(e) hinzufügen

Lösungsansatz: Zertifikatskette herunterladen und dem Truststore hinzufügen.

Der erste Ansatz, wie an die Zertifikate gelangt werden kann fand sich auf StackExchange:

openssl s_client -showcerts -servername deringo-dev.onelogin.com -connect deringo-dev.onelogin.com:443 | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > mycert.pem

Das funktioniert prinzipiell, dauert aber sehr lange. Außerdem wird in einem ausführlichen Kommentar darauf hingewiesen, dass die Intermediate Certificates so nicht gezogen würden.

Eine ausführliche Anleitung findet sich auf Baeldung, deren Ansatz ist wesentlich schneller (von mir nicht auf Intermediate C. getestet):

openssl s_client -connect deringo-dev.onelogin.com:443 -showcerts </dev/null | openssl x509 -outform pem > mycert.pem

Den Inhalt der heruntergeladenen Zertifikatsdatei in Plain Text anzeigen lassen:

openssl x509 -in mycert.pem -noout -text

Auf der Seite sind noch viele weitere Beispiele.

Die Zertifikate importieren:

cp mycert.pem /usr/local/share/ca-certificates/mycert.crt
update-ca-certificates

Umsetzung

Das Dockerfile des Reverse Proxies:

FROM httpd:2.4
RUN apt update && apt install -y \
        libapache2-mod-auth-openidc \
        ca-certificates
RUN openssl s_client -connect deringo-dev.onelogin.com:443 -showcerts </dev/null | openssl x509 -outform pem > mycert.pem && \
    cp mycert.pem /usr/local/share/ca-certificates/mycert.crt && \
    update-ca-certificates
RUN cp /usr/lib/apache2/modules/mod_auth_openidc.so /usr/local/apache2/modules/RUN mv conf/httpd.conf conf/container_httpd.conf
CMD ["httpd-foreground"]

Anschließend das Image neu bauen:

docker-compose build reverseproxy

Test

Leider kann momentan nur auf der Konsole getestet werden:

curl localhost/private/

Aber der Docker Output sieht nicht gut aus: "SSL certificate problem: unable to get local issuer certificate":

version2-reverseproxy-1  | [Tue Jun 07 13:48:25.115383 2022] [auth_openidc:error] [pid 9:tid 140428228966144] [client 172.21.0.1:57644] oidc_util_http_call: curl_easy_perform() failed on: https://deringo-dev.onelogin.com/oidc/2/.well-known/openid-configuration (SSL certificate problem: unable to get local issuer certificate)
version2-reverseproxy-1  | [Tue Jun 07 13:48:25.115513 2022] [auth_openidc:error] [pid 9:tid 140428228966144] [client 172.21.0.1:57644] oidc_provider_static_config: could not retrieve metadata from url: https://deringo-dev.onelogin.com/oidc/2/.well-known/openid-configurationversion2-reverseproxy-1  | 172.21.0.1 - - [07/Jun/2022:13:48:25 +0000] "GET /private/ HTTP/1.1" 500 531
version2-reverseproxy-1  | 172.21.0.1 - - [07/Jun/2022:13:48:27 +0000] "GET /private/ HTTP/1.1" 302 478

Allerdings, nach einem Neustart sieht es doch gut aus in der Konsole:

 curl localhost/private/
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>302 Found</title>
</head><body>
<h1>Found</h1><p>The document has moved <a href="https://deringo-dev.onelogin.com/oidc/2/auth?response_type=code&amp;scope=openid&amp;client_id=781a5c80-a77f-013a-c94a-020f214c554637671&amp;state=4RRlolG4XrN45Q3yCOc15Hf_6Ns&amp;redirect_uri=http%%3A%%2F%%2Flocalhost%%2Fprivate%%2Fredirect_uri&amp;nonce=B-PSe0ZSm6ZIoHebvpVtNQnv_JHqQLeSMpkI5tuoEi0">here</a>.</p>
</body></html>

Anschließend wieder gestoppt, Reverse Proxy Image neu bauen lassen, Container wieder gestartet: Beim ersten curl kommt der "SSL certificate problem: unable to get local issuer certificate"-Fehler, bei weiteren curls der "The document has moved"-Hinweis.

Schauen wir mal, wie das im Container aussieht:

Vorbereitung:

# frisch starten:
docker-compose down -v
docker-compose build reverseproxy
docker-compose up
# vor dem ersten Aufruf: Ab in den Container:
docker exec -it version2-reverseproxy-1 bash

Im Container:

# Im Container:
apt install curl

# 1. Aufruf
curl https://deringo-dev.onelogin.com/oidc/2/.well-known/openid-configuration
curl: (60) SSL certificate problem: unable to get local issuer certificate
More details here: https://curl.se/docs/sslcerts.html

curl failed to verify the legitimacy of the server and therefore could not
establish a secure connection to it. To learn more about this situation and
how to fix it, please visit the web page mentioned above.

# 2. Aufruf
curl https://deringo-dev.onelogin.com/oidc/2/.well-known/openid-configuration
curl: (60) SSL certificate problem: unable to get local issuer certificate
More details here: https://curl.se/docs/sslcerts.html

curl failed to verify the legitimacy of the server and therefore could not
establish a secure connection to it. To learn more about this situation and
how to fix it, please visit the web page mentioned above.

# 3. Aufruf
curl https://deringo-dev.onelogin.com/oidc/2/.well-known/openid-configuration
{"acr_values_supported":["onelogin:nist:level:1:re-auth"],"authorization_endpoint":"https://deringo-dev.onelogin.com/oidc/2/auth","claims_parameter_suppor[...]

Ich habe es noch ein paar mal ausprobiert, ungefähr jedes zweite bis dritte Mal hat es funktioniert.

Offensichtlich ist da noch ein LoadBalancer zwischen. 🤦‍♂️🤦‍♂️🤦‍♂️

Recherche

Im Container:

apt install iputils-ping

ping deringo-dev.onelogin.com

Mehrmaliges pingen gab zwei verschiedene IPs zurück.

apt install nmap

nmap deringo-dev.onelogin.com
Starting Nmap 7.80 ( https://nmap.org ) at 2022-06-07 14:18 UTC
Nmap scan report for deringo-dev.onelogin.com (52.29.255.229)
Host is up (0.0052s latency).
Other addresses for deringo-dev.onelogin.com (not scanned): 52.29.255.230
rDNS record for 52.29.255.229: ec2-52-29-255-229.eu-central-1.compute.amazonaws.com
Not shown: 994 filtered ports
PORT     STATE SERVICE
21/tcp   open  ftp
53/tcp   open  domain
80/tcp   open  http
443/tcp  open  https
554/tcp  open  rtsp
1723/tcp open  pptp

Aha! Es gibt zwei IPs zu dem Domainnamen und anscheinend ist OneLogin in den AWS.

Nochmal ein anderer Test; Wie ist das denn, wenn ich nicht im Container, sondern direkt vom Host curle:

curl https://deringo-dev.onelogin.com/oidc/2/.well-known/openid-configuration

Und siehe da: Auf dem Host funktioniert jeder Aufruf!

Mal schauen, ob wir die Certs finden:

locate *.crt
unter Anderen:
/etc/pki/ca-trust/source/anchors/ZscalerCloudChain.crt

Ab in den Container damit:

docker cp /etc/pki/ca-trust/source/anchors/ZscalerCloudChain.crt version2-reverseproxy-1:/tmp

im Container hinzufügen & testen:

cp /tmp/ZscalerCloudChain.crt /usr/local/share/ca-certificates/ZscalerCloudChain.crt
update-ca-certificates

curl https://deringo-dev.onelogin.com/oidc/2/.well-known/openid-configuration

Jeder Aufruf funktioniert, diesmal sieht es wirklich gut aus.

Umsetzung

Das Dockerfile des Reverse Proxies:

FROM httpd:2.4
RUN apt update && apt install -y \
        libapache2-mod-auth-openidc \
        ca-certificates
COPY /etc/pki/ca-trust/source/anchors/ZscalerCloudChain.crt /usr/local/share/ca-certificates/ZscalerCloudChain.crt
RUN update-ca-certificates
RUN cp /usr/lib/apache2/modules/mod_auth_openidc.so /usr/local/apache2/modules/
RUN mv conf/httpd.conf conf/container_httpd.conf
CMD ["httpd-foreground"]

Anschließend das Image neu bauen:

docker-compose build reverseproxy

Ich fasse es nicht:

Step 3/6 : COPY /etc/pki/ca-trust/source/anchors/ZscalerCloudChain.crt /usr/local/share/ca-certificates/ZscalerCloudChain.crt
1 error occurred:
        * Status: COPY failed: file not found in build context or excluded by .dockerignore: stat etc/pki/ca-trust/source/anchors/ZscalerCloudChain.crt: filedoes not exist, Code: 1

"you can only use files in your Dockerfile that are within the build context. Usually, this is ., so the Dockerfile's directory. " Copy file with absolute path to Docker Container using a Dockerfile - Stack Overflow

Nächster Versuch:

FROM httpd:2.4
RUN apt update && apt install -y \
        libapache2-mod-auth-openidc \
        ca-certificates
COPY ./ZscalerCloudChain.crt /usr/local/share/ca-certificates/ZscalerCloudChain.crt
RUN update-ca-certificates
RUN cp /usr/lib/apache2/modules/mod_auth_openidc.so /usr/local/apache2/modules/
RUN mv conf/httpd.conf conf/container_httpd.conf
CMD ["httpd-foreground"]
cp /etc/pki/ca-trust/source/anchors/ZscalerCloudChain.crt /app/DockerOneLoginApacheSample/version2/reverseproxy/ZscalerCloudChain.crt
docker-compose build reverseproxy
docker-compose up

Test

curl localhost/private/

Keine Fehler im Log! 🎉

Test im Browser mit Login

Steht noch aus, aktuell ist der Server nur über Console zu erreichen.

UPDATE: Inzwischen wurde der Zugriff per Browser auf den Server freigeschaltet (bzw. eine fehlerhafte Netzwerkkonfiguration gefixt) und die Public Seiten sind zugänglich.

Bei Aufruf der Private Seiten kommt allerdings eine Fehlermeldung:

Die Lösung wird im nächsten Post erarbeitet.

Categories
Java

Lokales Maven Repository

Aktuell migrieren wir eine Legacy Anwendung in eine neue Systemlandschaft und dabei wollen wir das Dependency Managment überarbeiten, das bisher aus einem Verzeichnis mit *.jar Library Dateien besteht, ohne Sourcecode. Wir wollen im Projekt Maven einführen. Das funktioniert überwiegend recht gut und einfach, indem wir die einzelnen *.jar Dateien durchgehen, die Versionsnummer bestmöglich raten und dann die entsprechende Abhängigkeit in die Maven Datei pom.xml hinzufügen. Die einzelnen Bibliotheken lassen sich gut über diese Seite finden: https://mvnrepository.com/

Allerdings gibt es auch firmeninterne oder propritäre Java Bibliotheken, diese lassen sich natürlich nicht über das zentrale Maven Repository finden.

Bei einem anderen Kunden haben wir zur Lösung dieses Problems einen eigenes, internes Repository aufgebaut: Sonatype Nexus. Dieses dient als Proxy für das öffentliche Maven Repository und zusätlich können hier die internen Bibliotheken hochgeladen und so verfügbar gemacht werden. Dieses Vorgehen kam bei dem aktuellen Projekt allerdings nicht in Betracht, so dass wir uns nach einer Alternative umgesehen haben. Das Dependency Managment nicht zu ändern wäre auch eine Alternative gewesen.

Die Alternative, die wir dann fanden, war das Einrichten eines im Projekt eingebetteten, lokalen Repositories. Die Idee dazu fanden wir in diesem Artikel: https://devcenter.heroku.com/articles/local-maven-dependencies

Das Vorgehen ist von der Idee her recht simpel: Im Projekt Ordner wird ein Ordner, zB maven/repository, angelegt und in diesem ein lokales Repository aufgebaut, welches dann in der pom.xml referenziert werden kann, um so von dort die internen Libraries verfügbar zu machen.

Repository anlegen

Im Projekt wird ein Verzeichnis für das lokale Repository angelegt, zB maven/repository.

Mittels des Maven deploy Befehls können dann die internen Libraries aus dem bisherigen Repository (aka WEB-INF/lib Folder) in das Maven Repository importiert werden.

Beispielsweise wird die firmeninterne companyLib.jar incl. Sourcecode in der Version 'latest', denn es gibt immer nur die letzte Version, installiert:

mvn deploy:deploy-file -Durl=file://C:/workspace/myLegacyProject/maven/repository/ -Dfile=companyLib-latest.jar -Dsources=companyLib-latest-sources.jar -DgroupId=de.deringo -DartifactId=companyLib -Dpackaging=jar -Dversion=latest

Das macht man dann für alle Libraries und kann anschließend das legacy Repository löschen.

Repository referenzieren

Das lokale Repository im Projekt wird wie folgt referenziert:

  <repositories>
    <repository>
      <id>project.local</id>
      <name>project</name>
      <url>file:${project.basedir}/maven/repository</url>
    </repository>
  </repositories>

Lokale Libraries einbinden

Die lokalen Libraries lassen sich wie gewohnt einbinden:

  <dependencies>
    <dependency>
      <groupId>de.deringo</groupId>
      <artifactId>companyLib</artifactId>
      <version>latest</version>
    </dependency>
    [...]
</dependencies>
Categories
Java

Generate Test Data

I need some test data to be displayed in my PrimeFaces Template App.

A good library to generate fake data is: Java Faker.

Add Java Faker to dependencies in Maven:

		<dependency>
			<groupId>com.github.javafaker</groupId>
			<artifactId>javafaker</artifactId>
			<version>1.0.2</version>
		</dependency>

For Example I want to have a Person with following fields:

	private String firstName;
	private String lastName;
	private Date dayOfBirth;
	private String phoneNumber;
	private String streetName;
	private String streetAddressNumber;
	private String zipCode;
	private String city;
	private String state;

A Person can be generated with fake data from Java Faker like this:

String firstName = faker.name().firstName();
String lastName = faker.name().lastName();
Date dayOfBirth = faker.date().birthday();
String phoneNumber = faker.phoneNumber().phoneNumber();
String streetName = faker.address().streetName();
String streetAddressNumber = faker.address().streetAddressNumber();
String zipCode = faker.address().zipCode();
String city = faker.address().city();
String state = faker.address().state();

Person person = new Person(firstName, lastName, dayOfBirth, phoneNumber, streetName, streetAddressNumber, zipCode, city, state);

Categories
Java

Test driven Json Analysis

To analyse an unknown Json API I setup a small project with Smallrye Rest Client to access the Json structure. I added JUnit for a test driven approach and Hamcrest for Matchers (like assertThat or is).

<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

	<modelVersion>4.0.0</modelVersion>
	<groupId>deringo</groupId>
	<artifactId>testproject</artifactId>
	<version>1.0-SNAPSHOT</version>
	<name>testproject</name>
	<description></description>

	<properties>
		<maven.compiler.source>8</maven.compiler.source>
		<maven.compiler.target>8</maven.compiler.target>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
	</properties>

	<dependencies>
		<!-- https://mvnrepository.com/artifact/org.junit.jupiter/junit-jupiter-api -->
		<dependency>
			<groupId>org.junit.jupiter</groupId>
			<artifactId>junit-jupiter-api</artifactId>
			<version>5.7.0</version>
			<scope>test</scope>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.hamcrest/hamcrest -->
		<dependency>
			<groupId>org.hamcrest</groupId>
			<artifactId>hamcrest</artifactId>
			<version>2.2</version>
			<scope>test</scope>
		</dependency>
		<!-- https://mvnrepository.com/artifact/io.smallrye/smallrye-rest-client -->
		<dependency>
			<groupId>io.smallrye</groupId>
			<artifactId>smallrye-rest-client</artifactId>
			<version>1.2.2</version>
		</dependency>
	</dependencies>

</project>
package deringo.testproject;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.junit.jupiter.api.Assertions.assertNotNull;

import javax.json.JsonArray;
import javax.json.JsonObject;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.junit.jupiter.api.Test;

public class TestJson {

	@Test
	public void testClientBuilderWorking() {
		Client client = ClientBuilder.newClient();
		WebTarget target = client.target("https://www.intensivregister.de/api/public/intensivregister");
		Response response = target.request(MediaType.APPLICATION_JSON).get();
		assertThat(response.getStatus(), is(200));
		JsonObject jo = response.readEntity(JsonObject.class);
		int rowCount = jo.getJsonNumber("rowCount").intValue();
		JsonArray ja = jo.getJsonArray("data");
		assertThat(ja.size(), is(rowCount));
		assertNotNull(ja.get(0).asJsonObject().getJsonObject("krankenhausStandort").getString("id"));

		ja.forEach(value -> 
				assertThat(
						value.asJsonObject().getString("id"),
						is(value.asJsonObject().getJsonObject("krankenhausStandort").getString("id"))
				));
	}

}
Categories
Java

Deploy to Tomcat with Maven

In my last post I decribed the way to build and deploy a war file to Tomcat application server with Ant.

In this post I show how to deploy the build war file to Tomcat application server with Maven.

Create inside the "ant" folder this Maven file:

<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>deringo</groupId>
    <artifactId>myApp</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <name>myApp</name>
    <description>myApp Maven deployment</description>

    <properties>
        <java.version>1.8</java.version>
        <tomcat.version>8.5.33</tomcat.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.apache.tomcat</groupId>
            <artifactId>tomcat-catalina</artifactId>
            <version>${tomcat.version}</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.0</version>
                <configuration>
                    <source>${java.version}</source>
                    <target>${java.version}</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>3.2.2</version>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                    <warName>myApp</warName>
                    <wtpContextName>myApp</wtpContextName>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>
                <version>2.2</version>
                <configuration>
                    <url>http://myAppServer:7011/manager/text</url>
                    <username>tomcat</username>
                    <password>tomcat</password>
                    <warFile>dist/myApp.war</warFile>
                    <path>/myApp</path>
                    <update>true</update>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

Execute with goal: tomcat7:deploy

Use Properties file

In my ANT file I have used a properties file for tomcat username/password etc. In my Maven script I want also to use this properties file.

Unfortunatly Maven can not handle property files out of the box. But there is a Plugin we can use:

        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>properties-maven-plugin</artifactId>
            <version>1.0-alpha-1</version>
            <executions>
                <execution>
                    <phase>initialize</phase>
                    <goals>
                        <goal>read-project-properties</goal>
                    </goals>
                    <configuration>
                        <files>
                            <file>tomcat.properties</file>
                        </files>
                    </configuration>
                </execution>
            </executions>
        </plugin>

This is the same, as writing this directly into pom.xml:

<properties>
    <tomcat.username>tomcat</tomcat.username>
    <tomcat.password>tomcat</tomcat.password>
</properties>

The complete pom.xml with properties:

<project xmlns="http://maven.apache.org/POM/4.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>deringo</groupId>
  <artifactId>myApp</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  <name>myApp</name>
  <description>myApp Maven deployment</description>

  <properties>
    <java.version>1.8</java.version>
    <tomcat.version>8.5.33</tomcat.version>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
      <groupId>org.apache.tomcat</groupId>
      <artifactId>tomcat-catalina</artifactId>
      <version>${tomcat.version}</version>
      <scope>provided</scope>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>properties-maven-plugin</artifactId>
        <version>1.0-alpha-1</version>
        <executions>
          <execution>
            <phase>initialize</phase>
            <goals>
              <goal>read-project-properties</goal>
            </goals>
            <configuration>
              <files>
                <file>tomcat.properties</file>
              </files>
            </configuration>
          </execution>
        </executions>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.8.0</version>
        <configuration>
          <source>${java.version}</source>
          <target>${java.version}</target>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-war-plugin</artifactId>
        <version>3.2.2</version>
        <configuration>
          <failOnMissingWebXml>false</failOnMissingWebXml>
          <warName>myApp</warName>
          <wtpContextName>myApp</wtpContextName>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.tomcat.maven</groupId>
        <artifactId>tomcat7-maven-plugin</artifactId>
        <version>2.2</version>
        <configuration>
          <url>${tomcat.manager.url}</url>
          <username>${tomcat.username}</username>
          <password>${tomcat.password}</password>
          <warFile>dist/myApp.war</warFile>
          <path>${webapp.name}</path>
          <update>true</update>
        </configuration>
      </plugin>
    </plugins>
  </build>

</project>

Update 2021-03-24

I tried the configuration in a project but got this error:

Plugin execution not covered by lifecycle configuration: org.codehaus.mojo:properties-maven-plugin:1.0-alpha-1:read-project-properties (execution: default, phase: initialize)

I solved the error adding a pluginManagement tag:

<build>
    <pluginManagement>
        <plugins>
            <plugin> ... </plugin>
            <plugin> ... </plugin>
                  ....
        </plugins>
    </pluginManagement>
</build>

But this solution seems more like a workaround when reading the discussion on stackoverflow.
...need to search further...

Use in Jenkins

I have not tried it, but it should be possible to set an environment variable in Jenkins build step to execute with a configurable filename.

For example TOMCAT_PROPERTIES=jenkins-home/secret/tomcat-dev.properties.
And we can use it in Maven script this way:

            <configuration>
              <files>
                <file>${env.TOMCAT_PROPERTIES}</file>
              </files>
            </configuration>