Saturday, July 13, 2019

Book: Spring Microservices in Action

This is a brilliantly written book.

Microservice Architecture


Flexible, Resilient, Scalable

IaaS, PaaS, SaaS, FaaS, CaaS

Client-side load balancing, Circuit breaker, Fallback, Bulkhead

Log correlation. Log aggregation. Microservice tracing

Spring Cloud:
Netflix Eureka (discovery), Zuul (routing), Ribbon (LN), Hystrix (Circuit Breaker), Sleuth/Uipkin (logging, tracing, aggregation), Oauth2/JWT Spring Security JavaScript Web Token

Hystrix proxies all RestTemplate. calls to add timeout. Ribbon also injects RestTemplate with all available service instances for LB and FO

to expose a bean there are 2 ways:
either one of @Component, @Service, @Repository
or @Configuration + @Bean

Apache Thrift, Apache Avro

12 factor apps: codebase in git, dependencies in maven, config in separate files, backing services (DB etc) cloud-ready,
immutable builds, stateless processes, port binding, horizontal scaling, disposable services, dev=prod, streamable logs (splunk, fluentd), scripted admin tasks.

Actuator health check.

Friday, July 12, 2019

dockerfile cmd and entrypoint

very confusing, poor design IMHO


FROM ubuntu
ENV myname "pierre"
ENTRYPOINT ["/bin/bash", "-c", "echo hello ${myname}"]

docker built -t hello01 .
docker run hello01

FROM ubuntu
ENTRYPOINT ["sleep"]

docker built -t hello02 .
docker run hello02

#this sleep for 5s
docker run hello02 5

#this gives error because parameter is missing
docker run hello02

FROM ubuntu
ENTRYPOINT ["sleep"]
CMD ["5"]

this version uses a default time of 5, if not specified in command line
"docker run hello02" will sleep for 5
"docker run hello02 10" will sleep for 10

Thursday, July 11, 2019

Java JSSE SSL flags

all turn on all debugging
ssl turn on ssl debugging

The following can be used with ssl:

record enable per-record tracing
handshake print each handshake message
keygen print key generation data
session print session activity
defaultctx print default SSL initialization
sslctx print SSLContext tracing
sessioncache print session cache tracing
keymanager print key manager tracing
trustmanager print trust manager tracing
pluggability print pluggability tracing
handshake debugging can be widened with:
data hex dump of each handshake message
verbose verbose handshake message printing

record debugging can be widened with:

plaintext hex dump of record plaintext
packet print raw SSL/TLS packets

Other non-so-famous properties:









Wednesday, July 10, 2019

kubectl generators and restart option

the only non-deprecated generatori is "run-pod/v1" :

kubectl run nginx --image=nginx --generator=run-pod/v1 --dry-run -o yaml

apiVersion: v1
kind: Pod
  creationTimestamp: null
    run: nginx
  name: nginx
  - image: nginx
    imagePullPolicy: IfNotPresent
    name: nginx
    resources: {}
  dnsPolicy: ClusterFirst
  restartPolicy: Always
status: {}

kubectl run nginx --image=nginx --dry-run -o yaml

apiVersion: apps/v1beta1
kind: Deployment
  creationTimestamp: null
    run: nginx
  name: nginx
  replicas: 1
      run: nginx
  strategy: {}
      creationTimestamp: null
        run: nginx
      - image: nginx
        name: nginx
        resources: {}
status: {}

#create nginx POD only

kubectl run nginx --image=nginx --port=80 --restart=Never --dry-run -o yaml

apiVersion: v1
kind: Pod
  creationTimestamp: null
    run: nginx
  name: nginx
  - image: nginx
    imagePullPolicy: IfNotPresent
    name: nginx
    - containerPort: 80
    resources: {}
  dnsPolicy: ClusterFirst
  restartPolicy: Never
status: {}

#create deployment nginx and pod

kubectl run nginx --image=nginx --port=80 --restart=Always --dry-run -o yaml

apiVersion: apps/v1beta1
kind: Deployment
  creationTimestamp: null
    run: nginx
  name: nginx
  replicas: 1
      run: nginx
  strategy: {}
      creationTimestamp: null
        run: nginx
      - image: nginx
        name: nginx
        - containerPort: 80
        resources: {}
status: {}

Friday, June 28, 2019

Helidon MicroProfiles

Quickstart Helidon SE

Quickstart Helidon MP

"MicroProfile is a collection of enterprise Java APIs that should feel familiar to Java EE developers. MicroProfile includes existing APIs such as JAX-RS, JSON-P and CDI, and adds additional APIs in areas such as configuration, metrics, fault tolerance and more."

More on MP

Saturday, June 22, 2019

maven-install-plugin copies files to your local .m2 repo

you can run this command from anywhere, no need for a pom.xml:

$ mvn install:install-file -Dfile=/c/pierre/downloads/ -DgroupId=pippo -DartifactId=pluto -Dpackaging=zip -Dversion=3.0
[INFO] Scanning for projects...
[INFO] ------------------< org.apache.maven:standalone-pom >-------------------
[INFO] Building Maven Stub Project (No POM) 1
[INFO] --------------------------------[ pom ]---------------------------------
[INFO] --- maven-install-plugin:2.4:install-file (default-cli) @ standalone-pom ---
[INFO] Installing C:\pierre\downloads\ to c:\pierre\.m2\repository\pippo\pluto\3.0\
[INFO] Installing C:\Users\pierl\AppData\Local\Temp\mvninstall5440042488979291271.pom to c:\pierre\.m2\repository\pippo\pluto\3.0\pluto-3.0.pom
[INFO] ------------------------------------------------------------------------
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 0.689 s
[INFO] Finished at: 2019-06-22T16:08:57+02:00
[INFO] ------------------------------------------------------------------------

and the generated pom.xml is

<?xml version="1.0" encoding="UTF-8"?>
<project xsi:schemaLocation="" xmlns=""
  <description>POM was created from install:install-file</description>

Wednesday, June 19, 2019

Spring Boot 2 HTTPS

see also

generate the self-signed certificate:

keytool -genkeypair -alias baeldung -keyalg RSA -keysize 2048 -storetype PKCS12 -keystore baeldung.p12 -validity 3650

and store it in src/main/resources/keystore folder



# The format used for the keystore. It could be set to JKS in case it is a JKS file
# The path to the keystore containing the certificate
# The password used to generate the certificate
# The alias mapped to the certificate

#trust store location
#trust store password

maven common plugins

For a very good overall tutorial on Maven, read this

For a list of most plugins














Sunday, June 16, 2019

Spring bean lifecycles and BeanPostProcessor

import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

public class MyComponent implements InitializingBean, DisposableBean {
public void afterPropertiesSet() throws Exception {
System.out.println("afterPropertiesSet from InitializingBean");

public void onPostConstruct() {

public void onPreDestroy() {

public void destroy() throws Exception {
System.out.println("destroy from DisposableBean ");


the sequence is:

afterPropertiesSet from InitializingBean
destroy from DisposableBean

and you can intercept instantiatio of every bean with a BPP :

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.annotation.Configuration;

public class CustomBeanPostProcessor implements BeanPostProcessor {

    public CustomBeanPostProcessor() {
        System.out.println("0. Spring calls constructor");

    public Object postProcessBeforeInitialization(Object bean, String beanName)
            throws BeansException {
        System.out.println(bean.getClass() + "  " + beanName);
        return bean;

    public Object postProcessAfterInitialization(Object bean, String beanName)
            throws BeansException {
        System.out.println(bean.getClass() + "  " + beanName);
        return bean;

fstab and UUID for device identification, docker and friends

on my VirtualBox Centos7:

cat /etc/fstab

/dev/mapper/cl-root / xfs defaults 0 0
UUID=70139d85-209e-4997-9d06-af6659221021 /boot xfs defaults 0 0
/dev/mapper/cl-swap swap swap defaults 0 0

this is:
[Device] [Mount Point] [File System Type] [Options] [Dump] [Pass]

ls -l /dev/disk/by-uuid/
total 0
lrwxrwxrwx. 1 root root 9 Jun 14 17:41 2019-05-13-13-58-35-65 -> ../../sr0
lrwxrwxrwx. 1 root root 10 Jun 14 17:41 27882150-dbcf-44a5-8461-a7e16020ee6f -> ../../dm-1
lrwxrwxrwx. 1 root root 10 Jun 14 17:41 70139d85-209e-4997-9d06-af6659221021 -> ../../sda1
lrwxrwxrwx. 1 root root 10 Jun 14 17:41 96e9a0f9-2b77-4cfc-be6e-f4c982e57123 -> ../../dm-0
lrwxrwxrwx. 1 root root 10 Jun 15 19:08 fdad3ac1-1c70-4371-8f9e-72ab7f0167df -> ../../dm-3

/dev/sr0: UUID="2019-05-13-13-58-35-65" LABEL="VBox_GAs_6.0.8" TYPE="iso9660"

on the host VM:

mount | sort

cgroup on /sys/fs/cgroup/blkio type cgroup (rw,nosuid,nodev,noexec,relatime,blkio)
cgroup on /sys/fs/cgroup/cpu,cpuacct type cgroup (rw,nosuid,nodev,noexec,relatime,cpuacct,cpu)
cgroup on /sys/fs/cgroup/cpuset type cgroup (rw,nosuid,nodev,noexec,relatime,cpuset)
cgroup on /sys/fs/cgroup/devices type cgroup (rw,nosuid,nodev,noexec,relatime,devices)
cgroup on /sys/fs/cgroup/freezer type cgroup (rw,nosuid,nodev,noexec,relatime,freezer)
cgroup on /sys/fs/cgroup/hugetlb type cgroup (rw,nosuid,nodev,noexec,relatime,hugetlb)
cgroup on /sys/fs/cgroup/memory type cgroup (rw,nosuid,nodev,noexec,relatime,memory)
cgroup on /sys/fs/cgroup/net_cls,net_prio type cgroup (rw,nosuid,nodev,noexec,relatime,net_prio,net_cls)
cgroup on /sys/fs/cgroup/perf_event type cgroup (rw,nosuid,nodev,noexec,relatime,perf_event)
cgroup on /sys/fs/cgroup/pids type cgroup (rw,nosuid,nodev,noexec,relatime,pids)
cgroup on /sys/fs/cgroup/systemd type cgroup (rw,nosuid,nodev,noexec,relatime,xattr,release_agent=/usr/lib/systemd/systemd-cgroups-agent,name=systemd)
configfs on /sys/kernel/config type configfs (rw,relatime)
debugfs on /sys/kernel/debug type debugfs (rw,relatime)
/dev/mapper/cl-root on / type xfs (rw,relatime,seclabel,attr2,inode64,noquota)
/dev/mapper/docker-253:0-34242903-3869b9e3d61005155d7ce7222280b67d4c034537b462d76016409d74c39c403b on /var/lib/docker/devicemapper/mnt/3869b9e3d61005155d7ce7222280b67d4c034537b462d76016409d74c39c403b type xfs (rw,relatime,seclabel,nouuid,attr2,inode64,logbsize=64k,sunit=128,swidth=128,noquota)
devpts on /dev/pts type devpts (rw,nosuid,noexec,relatime,seclabel,gid=5,mode=620,ptmxmode=000)
/dev/sda1 on /boot type xfs (rw,relatime,seclabel,attr2,inode64,noquota)
/dev/sr0 on /run/media/centos/VBox_GAs_6.0.8 type iso9660 (ro,nosuid,nodev,relatime,uid=1000,gid=1000,iocharset=utf8,mode=0400,dmode=0500,uhelper=udisks2)
devtmpfs on /dev type devtmpfs (rw,nosuid,seclabel,size=3989408k,nr_inodes=997352,mode=755)
fusectl on /sys/fs/fuse/connections type fusectl (rw,relatime)
gvfsd-fuse on /run/user/1000/gvfs type fuse.gvfsd-fuse (rw,nosuid,nodev,relatime,user_id=1000,group_id=1000)
hugetlbfs on /dev/hugepages type hugetlbfs (rw,relatime,seclabel)
mqueue on /dev/mqueue type mqueue (rw,relatime,seclabel)
nfsd on /proc/fs/nfsd type nfsd (rw,relatime)
proc on /proc type proc (rw,nosuid,nodev,noexec,relatime)
proc on /run/docker/netns/9c46943f17e7 type proc (rw,nosuid,nodev,noexec,relatime)
pstore on /sys/fs/pstore type pstore (rw,nosuid,nodev,noexec,relatime)
securityfs on /sys/kernel/security type securityfs (rw,nosuid,nodev,noexec,relatime)
selinuxfs on /sys/fs/selinux type selinuxfs (rw,relatime)
shm on /var/lib/docker/containers/55284026cd2880cf08c45e66754fcf8011c9cf3227f1564022afad7807cbee27/mounts/shm type tmpfs (rw,nosuid,nodev,noexec,relatime,seclabel,size=65536k)
sunrpc on /var/lib/nfs/rpc_pipefs type rpc_pipefs (rw,relatime)
sysfs on /sys type sysfs (rw,nosuid,nodev,noexec,relatime,seclabel)
systemd-1 on /proc/sys/fs/binfmt_misc type autofs (rw,relatime,fd=31,pgrp=1,timeout=0,minproto=5,maxproto=5,direct,pipe_ino=13854)
tmpfs on /dev/shm type tmpfs (rw,nosuid,nodev,seclabel)
tmpfs on /run type tmpfs (rw,nosuid,nodev,seclabel,mode=755)
tmpfs on /run/user/1000 type tmpfs (rw,nosuid,nodev,relatime,seclabel,size=801028k,mode=700,uid=1000,gid=1000)
tmpfs on /sys/fs/cgroup type tmpfs (ro,nosuid,nodev,noexec,seclabel,mode=755)

on the docker centos7 container:

mount | sort

/dev/mapper/cl-root on /etc/hostname type xfs (rw,relatime,seclabel,attr2,inode64,noquota)
/dev/mapper/cl-root on /etc/hosts type xfs (rw,relatime,seclabel,attr2,inode64,noquota)
/dev/mapper/cl-root on /etc/resolv.conf type xfs (rw,relatime,seclabel,attr2,inode64,noquota)
/dev/mapper/docker-253:0-34242903-3869b9e3d61005155d7ce7222280b67d4c034537b462d76016409d74c39c403b on / type xfs (rw,relatime,seclabel,nouuid,attr2,inode64,logbsize=64k,sunit=128,swidth=128,noquota)
cgroup on /sys/fs/cgroup/blkio type cgroup (ro,nosuid,nodev,noexec,relatime,blkio)
cgroup on /sys/fs/cgroup/cpu,cpuacct type cgroup (ro,nosuid,nodev,noexec,relatime,cpuacct,cpu)
cgroup on /sys/fs/cgroup/cpuset type cgroup (ro,nosuid,nodev,noexec,relatime,cpuset)
cgroup on /sys/fs/cgroup/devices type cgroup (ro,nosuid,nodev,noexec,relatime,devices)
cgroup on /sys/fs/cgroup/freezer type cgroup (ro,nosuid,nodev,noexec,relatime,freezer)
cgroup on /sys/fs/cgroup/hugetlb type cgroup (ro,nosuid,nodev,noexec,relatime,hugetlb)
cgroup on /sys/fs/cgroup/memory type cgroup (ro,nosuid,nodev,noexec,relatime,memory)
cgroup on /sys/fs/cgroup/net_cls,net_prio type cgroup (ro,nosuid,nodev,noexec,relatime,net_prio,net_cls)
cgroup on /sys/fs/cgroup/perf_event type cgroup (ro,nosuid,nodev,noexec,relatime,perf_event)
cgroup on /sys/fs/cgroup/pids type cgroup (ro,nosuid,nodev,noexec,relatime,pids)
cgroup on /sys/fs/cgroup/systemd type cgroup (ro,nosuid,nodev,noexec,relatime,xattr,release_agent=/usr/lib/systemd/systemd-cgroups-agent,name=systemd)
devpts on /dev/console type devpts (rw,nosuid,noexec,relatime,seclabel,gid=5,mode=620,ptmxmode=666)
devpts on /dev/pts type devpts (rw,nosuid,noexec,relatime,seclabel,gid=5,mode=620,ptmxmode=666)
mqueue on /dev/mqueue type mqueue (rw,nosuid,nodev,noexec,relatime,seclabel)
proc on /proc type proc (rw,nosuid,nodev,noexec,relatime)
proc on /proc/bus type proc (ro,relatime)
proc on /proc/fs type proc (ro,relatime)
proc on /proc/irq type proc (ro,relatime)
proc on /proc/sys type proc (ro,relatime)
proc on /proc/sysrq-trigger type proc (ro,relatime)
shm on /dev/shm type tmpfs (rw,nosuid,nodev,noexec,relatime,seclabel,size=65536k)
sysfs on /sys type sysfs (ro,nosuid,nodev,noexec,relatime,seclabel)
tmpfs on /dev type tmpfs (rw,nosuid,seclabel,size=65536k,mode=755)
tmpfs on /proc/acpi type tmpfs (ro,relatime,seclabel)
tmpfs on /proc/asound type tmpfs (ro,relatime,seclabel)
tmpfs on /proc/kcore type tmpfs (rw,nosuid,seclabel,size=65536k,mode=755)
tmpfs on /proc/keys type tmpfs (rw,nosuid,seclabel,size=65536k,mode=755)
tmpfs on /proc/sched_debug type tmpfs (rw,nosuid,seclabel,size=65536k,mode=755)
tmpfs on /proc/scsi type tmpfs (ro,relatime,seclabel)
tmpfs on /proc/timer_list type tmpfs (rw,nosuid,seclabel,size=65536k,mode=755)
tmpfs on /proc/timer_stats type tmpfs (rw,nosuid,seclabel,size=65536k,mode=755)
tmpfs on /sys/firmware type tmpfs (ro,relatime,seclabel)
tmpfs on /sys/fs/cgroup type tmpfs (ro,nosuid,nodev,noexec,relatime,seclabel,mode=755)

one can notice lot of differences in the VM and the container mounts, notably all the cgroup in docker are ro while in vm they are rw. Some mounts "/dev/mapper/cl-root on /etc/*" in docker

What is tmpfs?

What is xfs?

What is FUSE (fusectl) ?

Friday, June 14, 2019

bash comparison and validation of string

trying to understand Bash syntax is really wasted time.... just copy/paste working examples

array=("pippo pluto topolino")

[[ " ${array[@]} " =~ " ${value} " ]] && echo "YES" || echo "NO"

if [[ " ${array[@]} " =~ " ${value} " ]]; then echo trovato; fi

[[ $pippo = "ciao" ]] && echo "1yes"
[[ "ciao" = "ciao" ]] && echo "2yes"

if [ "$x" = "valid" ]; then
  echo "x has the value 'valid'"

[[ "$x" = "valid" ]] && echo "x is valid" 

[ "$x" == "valid" ] && echo "x has the value 'valid'"

[ "$x" == "valid" ] && echo "i am valid" || echo "i am invalid"

Tuesday, June 11, 2019

Java SSL server and client

this article is inspiring but it contains several errors/omissions.

The actually working code with detailed keytool commands is here

Ultimate resource to learn SSL handshake is

Sunday, June 9, 2019

shell testing

I have never seen in my life a bash shell being covered by automated tests.

I have thought of using Java and Mockito and Junit5, but it's not very straightforward to run shells from Java (in 2019.... maybe in 2 years it will be normal).

But I think it would be an excellent idea.

This is an inspiring article

This is the shunit2 framework:

Here the reference manual for shell scripting but it's a bit too academic. this one is richer of examples

PS shell scripting sucks


CRI-O = "Container Runtime Interface" "Open Container Initiative"
"a lightweight alternative to using Docker as the runtime for kubernetes"

"The CRI-O Container Engine is a implementation of a CRI (Kubernetes Container Runtime interface) that dedicated to Kubernetes. It implements only the features necessary to implement the CRI. Basically whatever Kubernetes needs. The goal to be as simple as possible and to never ever break Kubernetes. CRI-O is only for running containers in production. It runs OCI containers based on OCI images, which basically says it can run any container image sitting at, Quay.IO, or any other container registry. It also launches OCI containers with runc.

Docker has a whole bunch of different technology, but I am guessing you are asking about the Docker daemon. Docker daemon is a general purpose container engine that implements API for launching OCI Container using the same runc that CRI-O uses. Docker daemon supports multiple different orchestrators including the Docker Client, Docker Swarm, Kubernetes, Mesosphere. It also supports everything from playing with containers to building containers.

The team behind CRI-O believes that building containers and developing and playing with containers should be done by different tools than the container engine that is used by Kubernetes. The CRI-O team has developed the Podman and Buildah container engines for developing/playing with containers and building container images.

Since these three tasks are done separately CRI-O can run with much tighter security than is required for building and developing containers."

CRI-O and kubeadm

What is a "pause" container and a "PID namespace sharing" ?

What is Weave ?

What is a Nodeport ?

Saturday, June 8, 2019

Cloud-Native Applications in Java

excellent book covering basically EVERYTHING about the Java Cloud ecosystem.

Jakarta EE microprofiles, some readings

RHEL6 legacy services

just upgrade to RHEL7 please.... or RHEL8...

change keyboard to Swiss German:

vi /etc/sysconfig/keyboard


shutdown -r now

cat /etc/inittab should tell you id:5:initdefault: which is the default runlevel

runlevel checks current runlevel

system-config-services UI utility to configure services

service bla status

services are defined in /etc/rc.d/init.d/

ls /etc/xinetd.d here other services

ntsysv to enable/disable services to startup ( ntsysv --level 35 will edit runlevel 3 and 5)

chkconfig --list or chkconfig --list httpd

chkconfig httpd on or chkconfig httpd on --level 35
chkconfig httpd off or chkconfig httpd off --level 35

service --status-all

service httpd start

/var/lock/subsys/ -> " lock files created by their init scripts" see here

before start:
if [ ! -f /var/lock/subsys/servicename ]; then
start # start service here

at the end of start:
touch /var/lock/subsys/servicename

at the end of stop:
rm -f /var/lock/subsys/servicename

WARNING: stale files could linger if abrupt shutdown -> always check also existence of PID (must write PID file)

What happens at boot?
/etc/rc.d/rcN.d (N = current runlevel)

Template for service scripts is in /usr/share/doc/initscripts-*/sysvinitfiles

sudo stat /proc/1/exe -> /sbin/init
stat /sbin/init -> /lib/systemd/systemd
/sbin/init --version


Thursday, June 6, 2019

SSL renegotiation and resumption

"Resumption and renegotiation are rather opposites. Resumption restarts a previous TLS session in a new TCP connection, using the same TLS parameters. Renegotiation continues an existing TLS session in the same TCP connection, but changes some of the parameters.

in Fiddler, check for the renegotiation_info field in the CONNECT requestsmethods

Secure Renegotiation Supported
Secure Client-Initiated Renegotiation Yes
Insecure Client-Initiated Renegotiation No

Session resumption (caching) Yes
Session resumption (tickets) No

check DisableRenegoOnClient link and

"Modify the key to HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\SecurityProviders\SCHANNEL\DisableRenegoOnClient | DWORD=0" -Djdk.tls.rejectClientInitiatedRenegotiation=true ( see on why this is a bad idea)

Doc on Session Resumption


Here more explanation on Resumption and Renegotiation

To understand JSSE in general read this guide

viewing https handshakes in fiddler

Right-click the column bar and select Customize columns....

Collection: Miscellaneous
Field Name: RequestMethod

Thursday, May 30, 2019

branching models, trunk based development

the only good git presentations are VISUAL - unless you visualize what happens in terms of commits, there is NO WAY you can learn.

here they explain very well the meaning of -no-ff (no fast forward)

git merge --no-ff myfeature

"The --no-ff flag causes the merge to always create a new commit object, even if the merge could be performed with a fast-forward. This avoids losing information about the historical existence of a feature branch and groups together all commits that together added the feature. "

interesting the explanation of Feature branches, Release branches, Hotfix branches

Here great explanation of merge vs rebase

Really interesting what they say here:

Tuesday, May 28, 2019


I have just read/watched the Baeldung article on Codota

this thing seems to have a big future... as IT developer, I am often confronted with a blank screen and a "and now what?" and googling for working examples... with so many frameworks libraries languages etc, it's unrealistic to expect that every developer should remember all by heart... nor people having the discipline of building a collection of quickstarts/examples.

having an IDE who can guide you through the syntax of each specific framework is really enormously boosting productivity and self-confidence.

I will explore the tool when I have time

Sunday, May 19, 2019

JAXRS all-in-one

All annotations are summarized here

"Base URL for any web application is:


Append tag from web.xml with Base URL that forms:


Append class-level @Path(“class-level”) annotation and then method-level @Path(“method-level”) annotation that forms:


extends Application







@PathParam("isbn") String isbn



It's all very clear apart @Context... read here to understand @Context

this for SecurityContext :

and some more coding examples here

Friday, May 17, 2019

More interesting readings on quarkus and microprofiles

I reveive from my friend Rob:

This will soon overhaul Spring Boot. Look how they fast grow with integrating all enterprise patterns on Quarkus. This community is the driver

Look at this suberb documentation, almost covering everything you need

and then this amazing reactive streaming doc

this will leave spring boot behind really soon

Worth reading is also

Interesting also eclipse.microprofile running on Open Liberty

Thursday, May 16, 2019

Jooq and QueryDSL as alternatives to JPQL, Panache,

HQL (and JPQL) both suck because they are not statically typed..."lack of type safety and absence of static query checking" "concatenation of strings which is usually very unsafe "

"Criteria Query API ended up very verbose and practically unreadable. "

"jOOQ generates Java code from your database and lets you build type safe SQL queries through its fluent API. "

So this is no ORM framework, it uses your DB as it is, it simply allows you to write safer SQL queries directly in a fluent Java API. No Hocus-Pocus, it's a 1-to-1 mapping between DB and Java.

Here some examples

how to use it and

If you want to use Native SQL or JPQL in Spring:

This is the horribly verbose JPA Criteria API
" the main and most hard-hitting advantage of Criteria queries over HQL is the nice, clean, Object Oriented API."

Apache SSL and ciphersuites

Useful commands and links

openssl ciphers -v

httpd -v
httpd -V

openssl s_client -connect

yum list all
yum install nmap

nmap -p 443 --unprivileged -script ssl-enum-ciphers

SSLCipherSuite HIGH:!aNULL:!MD5

SSLCipherSuite HIGH:!aNULL:!MD5:!SSLv3:!TLSv1

443/tcp open  https
| ssl-enum-ciphers: 
|   SSLv3: No supported ciphers found
|   TLSv1.0: No supported ciphers found
|   TLSv1.1: No supported ciphers found
|   TLSv1.2: 
|     ciphers: 
|       TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 - strong
|       TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 - strong
|       TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 - strong
|       TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 - strong
|       TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 - strong
|       TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 - strong
|       TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 - strong
|       TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 - strong
|       TLS_RSA_WITH_AES_128_CBC_SHA256 - strong
|       TLS_RSA_WITH_AES_128_GCM_SHA256 - strong
|       TLS_RSA_WITH_AES_256_CBC_SHA256 - strong
|       TLS_RSA_WITH_AES_256_GCM_SHA384 - strong
|     compressors: 
|       NULL
|_  least strength: strongÉvariste_Galois

talking about GCM ciphers

yarn react and materialui

open cmd with admin rights:
choco install yarn
close this cmd and open a "normal" cmd

yarn create react-app app
cd app
yarn add bootstrap@4.1.3 react-cookie@3.0.4 react-router-dom@4.3.1 reactstrap@6.5.0
yarn add @material-ui/core
yarn start

in App.js:

import React, {Component} from 'react';
import './App.css';
import Button from '@material-ui/core/Button';
import Table from '@material-ui/core/Table';
import TableRow from '@material-ui/core/TableRow';
import TableCell from '@material-ui/core/TableCell';

Friday, May 10, 2019

CDI in IntelliJ Java Enterprise projects

I was following this tutorial to deploy a Primefaces application to Wildfly 16, but I kept getting an error

unable to find cdi beanmanager

I have tried adding Maven support and adding the dependency




to no avail.

Funnily, setting webapp version="2.3" instead of version="4.0" in web.xml fixes the problem.

Then I added CDI support as shown here:

and using version="4.0" and things are working.

good old friend JMeter

JMeter is one of those primitive animals that never goes extinct.

Decent presentation:

Excellent comparison with SoapUI

JMeter is good for a VERY quick and dirty PERFORMANCE test of a service.

Incorporating JMeter Performance tests in Maven builds: and this is the plugin

Some books on the topic:

Sai Matam, Jagdeep Jain - Pro Apache JMeter_ Web Application Performance Testing Apress (2017)

Bayo Erinle - JMeter Cookbook Packt Publishing (2014)

Bayo Erinle - Performance Testing with JMeter 3 Enhance the performance of your web application Packt Publishing (2017)

GraalVM native image

download GraalVM CE and unzip it to /home/centos/graalvm-ce-19.0.0/

export JAVA_HOME=/home/centos/graalvm-ce-19.0.0/
export GRAALVM_HOME=/home/centos/graalvm-ce-19.0.0/

cd /home/centos/graalvm-ce-19.0.0/bin
./java -version
sudo ./gu install native-image


public class HelloWorld {
        public static void main(String[] args) {
            System.out.println("hello world");


time ./java HelloWorld

hello world

real 0m0.074s
user 0m0.057s
sys 0m0.019s

./native-image -H:+ReportExceptionStackTraces HelloWorld

Build on Server(pid: 6249, port: 45750)
[helloworld:6249]    classlist:     299.78 ms
[helloworld:6249]        (cap):     359.96 ms
[helloworld:6249]        setup:     479.50 ms
Error: Basic header file missing (). Make sure headers are available on your system.$UserException: Basic header file missing (). Make sure headers are available on your system.
 at java.util.concurrent.ForkJoinTask$AdaptedRunnableAction.exec(
 at java.util.concurrent.ForkJoinTask.doExec(
 at java.util.concurrent.ForkJoinPool$WorkQueue.runTask(
 at java.util.concurrent.ForkJoinPool.runWorker(
Error: Image build request failed with exit status 1

sudo yum install glibc-devel
sudo yum install zlib-devel
sudo yum install gcc

./native-image HelloWorld

time ./helloworld
hello world

real 0m0.012s
user 0m0.001s
sys 0m0.011s


Monday, May 6, 2019


This is an excellent book - not only about technology but mostly about culture, leadership, teamwork, innovation.

I don't share the enthusiastic vision of the author for which life is about serving corporations to beat competition and cut jobs. However it's an educational book.

JDK maven Nexus and HTTPS

If your Nexus repository uses certificates signed by your own Root CA, chances are that a JDK doesn't trust them.

Then when you run

mvn package

you get PKIX path building failed:
unable to find valid certification path to requested target

Go to your JAVA_HOME\jre\lib\security folder, where the cacerts file is located, and issue

keytool -list -v -keystore cacerts

enter "changeit" as password

this shold tell you all your trusted CAs

You should import your own CA certificate to into this keystore.

I have tried also setting:

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

but it disn't work for me.

Panache as a wrapper for Hibernate

The product seems very well conceived, it really streamlines your JPA code.

One more aspect where the Java world has completely screwed up, is the 20 different ways you can implement DB queries....
ah if only ORM had been embedded into the language from the beginning, we would be dealing with a single persistence framework.

Thursday, May 2, 2019

Enabling Swagger in a Java EE application

This should be enough:

0) add Maven dependencies:


1) with an Application, register the Swagger jaxrs resources:

import java.util.Set;


public class JaxRsActivator extends Application {

 public Set<Class<?>> getClasses() {
  Set<Class<?>> resources = new java.util.HashSet<>();
//  resources.add(BearerTokenFilter.class);
  return resources;

 private void addRestResourceClasses(Set<Class<?>> resources) {


2) register the Swagger configuration:

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;

import com.wordnik.swagger.config.ConfigFactory;
import com.wordnik.swagger.config.ScannerFactory;
import com.wordnik.swagger.config.SwaggerConfig;
import com.wordnik.swagger.jaxrs.config.DefaultJaxrsScanner;
import com.wordnik.swagger.jaxrs.reader.DefaultJaxrsApiReader;
import com.wordnik.swagger.reader.ClassReaders;

@WebServlet(name = "SwaggerJaxrsConfig", loadOnStartup = 1)
public class SwaggerJaxrsConfig extends HttpServlet {

 public void init(ServletConfig servletConfig) {
  try {
   SwaggerConfig swaggerConfig = new SwaggerConfig();
   ScannerFactory.setScanner(new DefaultJaxrsScanner());
   ClassReaders.setReader(new DefaultJaxrsApiReader());
  } catch (ServletException e) {

3) then you can annotare your services methods:

import javax.inject.Inject;
import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;
import com.wordnik.swagger.annotations.ApiResponse;
import com.wordnik.swagger.annotations.ApiResponses;

@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON })
@Api(value = "/pippo", description = "REST service end-points exposed to Pippo")
public class PippoService {
 @ApiOperation(value = "All Pippos", notes = "List all Pippos")
 @ApiResponses(value = { @ApiResponse(code = 200, message = "OK"), @ApiResponse(code = 500, message = "Server error, check log files") })
 public List listPippobyQuery(
                 @ApiParam(value = "the hostname where Pippo resides") @QueryParam("hostname") String hostName) {

  return listPippo(hostName);

Monday, April 29, 2019

JAXRS client with Jersey

As usual we start from the excellent Baeldung

The working solution is in and the client is in the test directory (Jersey is provided with "test" scope, while the "main" can be built with maven and deployed to WebLogic for instance)

The project is to turn the Service in a set of services with different types of payloads (JSON, XML, binary) and different marshaling/unmarshaling frameworks (Jexson, GSON...) , then run some performance test (using junit5) under different load conditions.

Swagger for Java EE reasteasy or jersey

Making Swagger work in Spring is very easy.

You can use it also in Java EE (Wildfly, WebLogic, even Tomcat!!! )

but all the documentation I have found is a bit outdated:

I have tried APIEE and but it's not showing my services and I see no error.

Some other outdated articles:

I have no time now, but if I need to write REST services in Java EE I would not live without Swagger...

Gradle deploy to Nexus

mkdir /home/centos/gitclones/gradletest
cd /home/centos/gitclones/gradletest
gradle init --type java-application

gradle build

vi build.gradle
add to plugins:
id 'maven'

maven Plugin for Gradle is documented here

gradle install

ls -ltra /home/centos/.m2/repository/gradletest/unspecified/
total 4956
-rw-r--r-- 1 centos docker 2371522 Apr 29 13:23
-rw-r--r-- 1 centos docker 2693120 Apr 29 13:23 gradletest-unspecified.tar
-rw-r--r-- 1 centos docker     752 Apr 29 13:23 gradletest-unspecified.jar
-rw-r--r-- 1 centos docker     756 Apr 29 13:23 gradletest-unspecified.pom

cat /home/centos/.m2/repository/gradletest/unspecified/gradletest-unspecified.pom


group and version are missing!

then you can follow the steps here

you define the group and version in your projects' build.gradle, you define nexus username/password/url in ~/.gradle/ and you use the maven-publish plugin to publish to Nexus

IntelliJ IDEA Essentials

this is a really precious book, very focused and essential, to learn very practical tricks on how to use Intellij effectively

Sunday, April 28, 2019

JPG to PDF conversion in Java

Create a Spring Initializer App (plain vanilla)

add this dependency: com.itextpdf:itextpdf:5.5.13

run this code

package org.pierre.jpgtopdf;

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import com.itextpdf.text.Document;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfWriter;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class JpgtopdfApplication implements CommandLineRunner {

    public static void main(String[] args) {, args);

    public void run(String... args) throws Exception {
        File root = new File("D:\\pierre\\tasse2019\\");
        String outputFile = "output.pdf";
        List<String> files = new ArrayList<String>();
        String[] alljpgs = root.list((dir, name) -> name.endsWith("jpg"));

        Document document = new Document();
        PdfWriter.getInstance(document, new FileOutputStream(new File(root, outputFile)));;
        for (String f : files) {
            Image image = Image.getInstance(new File(root, f).getAbsolutePath());
            image.setAbsolutePosition(0, 0);

It's amazingly fast!

CDI and javax.transaction.TransactionScoped

I was wondering how TransactionScoped works, and I stumbled upon this wonderful example:

This also is a great explanation on Injected beans

It's so clearly explained that I was deeply impressed by this
Gonçalo Marques. We need more of this stuff. Often people post partial, overcomplicated examples.... Gonçalo instead goes straight to the point.

Tuesday, April 23, 2019

Jenkins enable project based security

Sometimes you share a Jenkins instance amongst several projects (IMHO this is bad practice, each project should have its own Jenkins to minimize interference)

This is how to do it (copied from )

a) make sure Matrix Authorization Strategy Plugin is installed (Manage Jenkins/Manage Plugins/Installed Plugins)

b) "Manage Jenkins", "Configure Global Security", add the target user to the "Project-based Matrix Authorization Strategy ",
add the target user with permissions "Overall/Read and Job/Read"

c) on the main page, select the target project, "Enable project-based security", add the target user and on the right, click on the "grant all permissions" button

at this point the user has login and can administer the target project, but only view other projects.

Jenkins would be a much better tool if all these configuration operations could be easily scriptable. Nowadays it's just a huge clickodrome and very awkward to manage, you have to wade through zillion of configuration pages and unless you are really experienced it's sometimes frustrating ... you don't even have a "search" functionality for configuration options, you have to remember all locations by heart...

Sunday, April 21, 2019

Simple Spring Boot and React working example

Matt Raible is a boss and he is so straight to the point and precise.

Remember that if you have in your pom.xml the dependency spring-boot-starter-security, then Spring Boot will enable security by default with username "user" and a dynamically generated password:

so for the time being I have excluded this dependency.

This should explain more how to handle web security with the great fluent api provided by Spring.

Friday, April 19, 2019

Intellij and WebLogic

Wednesday, April 17, 2019

never copy/paste from outlook or Word

Microsoft sucks

The command on the left was copied from an email (Outlook). And it was failing, returning EVERYTHING, not only config.xml.

Then I have typed all over again (right pane) and it was working

Visually they look absolutely the same, even in Notepad++. But a closer inspection reveals hidden chars.

Copying and pasting from Outlook or Word has caused more victims than the 1919 Spanish Flu.

I remember a production delivery failed because someone copied a command from a Word document where Word had capitalized a property name.


package com.example.demo;

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

public class DemoApplication implements CommandLineRunner {

    public static void main(String[] args) {, args);

    public void run(String... args) throws Exception {
        CompletableFuture<String> completableFuture = new CompletableFuture<String>();
        completableFuture.complete("Future's Result");

        String result = completableFuture.get();

        CompletableFuture<Void> future = CompletableFuture.runAsync(new Runnable() {
            public void run() {
                // Simulate a long-running Job
                try {
                } catch (InterruptedException e) {
                    throw new IllegalStateException(e);
                System.out.println("I'll run in a separate thread than the main thread.");
        // Block and wait for the future to complete


Ruminations about Jenkins

The jobs are defined in here:


For every project (item), there is a folder.

In every folder there is a config.xml file which hopefully should contain the entire project definition.

My assumption is that one should simply save the config.xml, and this is enough to recreate the project elsewhere.

I am worried because the Project definitions in Jenkins are not saved in bitbucket,
and we don’t have an automated way to export them from PROD and import them to a UAT instance.

One COULD tar the $JENKINS_HOME/jobs folder, but it’s very bulky.

[jobs]$ cd myproject/

[myproject]$ ls -ltra

drwxr-xr-x. 3 pippo pippogroup 4096 Jul 18 2016 modules
-rw-r--r--. 1 pippo pippogroup 6 Apr 25 2018 nextBuildNumber
lrwxrwxrwx. 1 pippo pippogroup 26 Apr 25 2018 lastSuccessful -> builds/lastSuccessfulBuild
lrwxrwxrwx. 1 pippo pippogroup 22 Apr 25 2018 lastStable -> builds/lastStableBuild
drwxr-xr-x. 5 pippo pippogroup 4096 Apr 25 2018 workspace
drwxr-xr-x. 24 pippo pippogroup 4096 Apr 25 2018 builds
-rw-r--r--. 1 pippo pippogroup 7257 Apr 25 2018 config.xml
drwxr-xr-x. 5 pippo pippogroup 4096 Apr 25 2018 .
drwxr-xr-x. 360 pippo pippogroup 20480 Mar 18 15:06 ..

especially the workspace is a PIG

So for the time being I will simply tar up all the config.xml and untar them in UAT:


find . –maxdepth 2 –name config.xml | tar cvf /var/tmp/alljenkinsconfig.tar –T –

(maxdepth is important to avoid picking up files coming from the workspaces)

However we should really really IMHO push all those config.xml to bitbucket, regularly – ideally automatically whenever someone changes a config.xml:

git init
#set origin and remote
find . –maxdepth 2 –name config.xml –exec git add {} \;
git commit -m "blablabla"
git push

Incidentally, many project folders contain spaces, which makes it much trickier to write scripts to manipulate them.

I am not in favor of Capital Punishment, apart from cases when people create folders containing spaces.

Jenkins sucks anyway. Design is from Napoleonian Era, UI made by a freak, configuration freakishly XML based without fluent Administration Groovy API,
actually in the old times they were much better at designing stuff, think of the Tour Eiffel or the Pyramids and the Coliseum.
Nowadays any idiotic monkey can code freakish products like Maven or Jenkins and become a celebrity.

Thread dumps analysis

this post provides useful insights on how to detect issues from a Thread Dump:

For a quick thread dump consolidation one can use or (both are quite equivalent)....

Problem is that these tools are Application Server agnostic and don't tell you what is normal and what is not. I think some AI should be added to the tool, plus some graphical rendering for instance of the lock analysis.

When I have time I want to look into

Anyway advanced thread analysis is a skill in itself and should be done with proper tooling... manually sorting stuff can be overwhelming for the regular human being.

Saturday, April 13, 2019

Mockito revisited

I have used Mockito in 2010. Then I never did SERIOUS Java development any more (shame on me...)

Yet I strongly believe that a solid implementation of Mocks is the foundation of healthy, fully testable software.
If you can't entirely automate your application tests, you are playing with your life.


source code is here

List mockedList;

List spiedList = new ArrayList();

ArgumentCaptor argCaptor;

I am getting : Illegal reflective access by org.mockito.internal.util.reflection.AccessibilityChanger
Hopefully Mockito folks will fix this one da.

Wednesday, April 10, 2019

Gradle plugin for Jenkins

Maven Sucks, so we welcome Gradle - it can't possibly be worse than Maven!

it seems that Gradle Plugin is installed as part of the "common plugins". I use an old Jenkins 2.138.

export GRADLE_HOME=/home/centos/gradle/gradle-4.8
#make sure $GRADLE_HOME/bin is in $PATH
cd /home/centos/gitclones
git clone
cd gradle-simple/
gradle clean
gradle build
#check if jar was built
ls -ltra build/libs

I configure a freestyle Jenkins item to checkout from Github and "clean build" as gradle tasks...
Then I inspect /home/centos/.jenkins/workspace/gradletest/build/libs/ and the jar has been built there... great!

If I want to copy the plugin to another machine, it's in /home/centos/.jenkins/plugins/gradle.jpi


Manifest-Version: 1.0
Plugin-Dependencies: structs:1.3
Long-Name: Gradle Plugin
Compatible-Since-Version: 1.0
Plugin-Developers: Stefan Wolf:wolfs:
Group-Id: org.jenkins-ci.plugins
Extension-Name: gradle
Plugin-Version: 1.31
Jenkins-Version: 1.651.3
Short-Name: gradle

Tuesday, April 9, 2019

Effective Java third edition

the source code:

*clone (p. 86)
copy constructor/ copy factory
java.util.Comparator.comparingInt + thenComparingInt

immutable objects

composition over inheritance

default methods

generics and collections

unbounded wildcard types (<?>)

PECS producer extends consumer super



Monday, April 8, 2019

Generics and collections

this one has no compilation errors:

Set a;
Set<Object> b;
Set<? super Object> c;

a = new HashSet();
b = new HashSet<>();
c = new HashSet<>();

c = a;
c = b;
b = a;
b = c;
a = c;
a = b;

but if I use

Set<Object> b;
Set<?> c;

then "c = b" gives compilation error

Error:(26, 13) java: incompatible types: java.util.Set cannot be converted to java.util.Set

This is interesting, since ? means "any Object and subclasses"... while "? super Object" means "Object and its superclasses"
but Object has no superclasses, so effectively it's only Object.

If I use:
b = new HashSet<>();
Set<?? extends Object> c;

b = c;
fails with the same error:

Error:(26, 13) java: incompatible types: java.util.Set cannot be converted to java.util.Set

The raw type a can be assigned all the time to all the others.

similarly, collections are INVARIANT:
Set<Number> numset = new HashSet<>();
Set<Integer> intset = new HashSet<>();
Set<?> allset = new HashSet<>();

numset = intset; // INVALID
intset = numset; // INVALID
allset = numset; // VALID
numset = allset; // INVALID

but arrays are COVARIANT:

Number[] numarr = new Number[1];
Integer[] intarr = new Integer[1];
numarr = intarr; // VALID
intarr = numarr; // INVALID

Sunday, April 7, 2019

Amazing brushes by Reto

a colleague of mine, Reto, is a passionate photographer and Photoshop artist , here some links to his creations:

Intellij , maven and the source or target java language level

I create a new Java "maven" project, set it to Java 12 (ctrl-alt-shift-S, MOdules, Language level), but when I build I get:

"Warning:java: source value 1.5 is obsolete and will be removed in a future release"

Apparently this is due to the prehistoric, nonsensical Maven Compiler Plugin using Java 1.5 by default

you can either insert in the pom.xml :




Remember also to make sure that ctrl-alt-S (Settings) Settings -> Build, Execution, Deployment -> Build Tools -> Maven -> Importing is set to use JDK 12. So complicated. So brittle. So Maven.

Working with Maven is like traveling back to prehistoric times, like the Mural de la Prehistoria in Cuba,

developers on the right about to be eaten by Maven on the left

Priceless String manipulation Intellij plugin

ctrl-alt-S, then "Plugins" search for "String Manipulations"; install and reboot.

for instance, if you need to "escape XML" (that is transform reserve chars in "% bla ;" sequences :

File/new scratch file (or ctrl-alt-shift-ins), paste your XML, select all, right click "String manipulation", "escape xml"

Normally I used Notepad++ and the "XML Tools Plugin", but this seems more useful.

Wednesday, April 3, 2019

git synchronize repositories

It happens that an external Git repository has to be mirrored internally in a corporate git repository. This cloning and mirroring should include branches, tags, commit history etc. and be one-way (internal changes are lot upon synchronization)

Luckily you don't have to write special scripts, all is provided by git:

Let's make an experiment

in github I create a "gitclonesource" and a "gitclonedestination" empty repositories

mkdir gitclonetests
cd gitclonetests

#let's prepare the source
mkdir gitclonesource
cd gitclonesource
git init
echo "ciao" >
git add
git commit -m "first commit"
git remote add origin
git push -u origin master

#create branch
git checkout -b mybranch
echo "hello" >> mybranch.txt
git add mybranch.txt
git commit -am "added mybranch.txt"
git push --set-upstream origin mybranch

#create tag
git checkout master
git tag -a v1.4 -m "my version 1.4"
git push --tags

#now clone source and push to destination with all branches and tags
cd ..
#this will create a folder gitclonesource.git
git clone --bare
#when you cd, you will see a message BARE:master if using Git bash
cd gitclonesource.git/
git push --mirror

Counting objects: 7, done.
Delta compression using up to 8 threads.
Compressing objects: 100% (4/4), done.
Writing objects: 100% (7/7), 600 bytes | 200.00 KiB/s, done.
Total 7 (delta 0), reused 0 (delta 0)
 * [new branch]      master -> master
 * [new branch]      mybranch -> mybranch
 * [new tag]         v1.4 -> v1.4

and, lo and behold, in the gitclonedestination I can find my branch and the tag! All cloned in one go!

at this point you can cleanup the gitclonedestination.git:

cd ..
rm -rf gitclonedestination.git

Monday, April 1, 2019

WebLogic Security documentation JACC "Java Authorization Contract for Containers" java.lang.SecurityManager

Java Authentication Service Provider Interface for Containers (JASPIC)

Training Material:

Old book

Best Spring books

reblogging for my own reference, I am planning to read all those 5 books...

- Spring in Action 5
- Cloud Native Java
- Learning Spring Boot 2.0
- Spring 5 Recipes
- Spring Microservices in Action

I am already going through but I find it incredibly non-concise - lot of repeated stuff, very lengthy and boring coding sessions where you don't really see much new, lot of unnecessary verbosity. Not my style, I like crisp, focused, simple examples and just fundamental facts and concepts.

Saturday, March 30, 2019

Java EE 8 Application Development book

David R. Heffelfinger - Java EE 8 Application Development-Packt Publishing (2017)

I am going through the examples of the book, using WLS (it supports only Java EE 7, unfortunately), and IntelliJ 2019.1

here how to setup your environment (very easy!) :

Code is here

You can run also on Wildfly 16 which supports Java EE 8

Java EE 8 Javadoc

Friday, March 29, 2019

bash script cheatsheet

Tuesday, March 26, 2019

Camel rediscovered

testing rest with

Old posts:

Helm tutorials on Katacoda

I have been through some youtube tutorials on Helm but I found them too blablaistic. I like essential, crisp and down to earth presentations, not all-encompassing philosophical sermons.

curl | bash
helm init
helm repo update
kubectl get pods -n kube-system
helm version

in Chart.yaml there is basically nothing (version and chartname)

in equirements.yaml there are dependencies

in templates/configmap.yaml the ConfigMap

in templates/service.yaml the Service Definition (with port/nodePort)

in templates/pv.yaml the PersistenVolume

helm dependency update lets-chat

helm inspect lets-chat

helm install lets-chat --name demo -f my_values.yml --debug --dry-run

helm install lets-chat --name demo --namespace demo -f my_values.yml

helm list

helm status demo

kubectl get pods -n demo

sed -i 's/0.4.7/0.4.6/g' lets-chat/Chart.yaml

helm upgrade demo lets-chat --set replicas=2

helm history demo

helm rollback demo 1

maven the reference guide the complete reference usual excellent Baeldung tutorial to understand those obfuscated concepts of "lifecycle", "phase", "goal"

Monday, March 25, 2019

Book: java by comparison by Simon Harrer, Jörg Lenhard, Linus Dietz

Interesting book, concise and a breeze to read

Source code is here

My first (not very functional) implementation of FizzBuzz:


public class ConsoleBasedFizzBuzz implements FizzBuzz {
    public static void main(String[] args) {
        FizzBuzz fizzBuzz = new ConsoleBasedFizzBuzz();
        fizzBuzz.print(1, 100);

    private static void accept(int i) {
        StringBuffer result = new StringBuffer();
        if (i % 3 == 0) result.append("Fizz");
        if (i % 5 == 0) result.append("Buzz");
        if (result.length() == 0) result.append(i);

    public void print(int from, int to) {
        IntStream.range(from, to).forEach(ConsoleBasedFizzBuzz::accept);

"Any fool can write code that a computer can understand. Good programmers write code that humans can understand."

Avoid Unnecessary Comparisons
Avoid Negations
Return Boolean Expressions Directly
Simplify Boolean Expressions
Avoid NullPointerException in Conditionals
Avoid Switch Fallthrough
Always Use Braces
Ensure Code Symmetry
Replace Magic Numbers with Constants
Favor Enums Over Integer Constants
Favor For-Each Over For Loops
Avoid Collection Modification During Iteration
Avoid Compute-Intense Operations During Iteration
Group with New Lines
Favor Format Over Concatenation
Favor Java API Over DIY
Remove Superfluous Comments
Remove Commented-Out Code
Replace Comments with Constants
Replace Comments with Utility Methods
Document Implementation Decisions
Document Using Examples
Structure JavaDoc of Packages
Structure JavaDoc of Classes and Interfaces
Structure JavaDoc of Methods
Structure JavaDoc of Constructors
Use Java Naming Conventions
Follow Getter/Setter Conventions for Frameworks
Avoid Single-Letter Names
Avoid Abbreviations
Avoid Meaningless Terms
Use Domain Terminology
Fail Fast
Always Catch Most Specific Exception
Explain Cause in Message
Avoid Breaking the Cause Chain
Expose Cause in Variable
Always Check Type Before Cast
Always Close Resources
Always Close Multiple Resources
Explain Empty Catch
Structure Tests Into Given-When-Then
Use Meaningful Assertions
Expected Before Actual Value
Use Reasonable Tolerance Values
Let JUnit Handle Exceptions
Describe Your Tests @DisplayName @Disabled
Favor Standalone Tests
Parametrize Your Tests @ParameterizedTest @ValueSource
Cover the Edge Cases
Split Method with Optional Parameters
Favor Abstract Over Concrete Types
Favor Immutable Over Mutable State
Combine State and Behavior
Avoid Leaking References (defensive copying)
Avoid Returning Null
Favor Lambdas Over Anonymous Classes
Favor Method References Over Lambdas
Avoid Side Effects
Use Collect for Terminating Complex Streams
Avoid Exceptions in Streams
Favor Optional Over Null (Optional.ofNullable())
Avoid Optional Fields or Parameters
Use Optionals as Streams

Google Java Style Guide

Automate Your Build
Favor Logging Over Console Output
Minimize and Isolate Multithreaded Code
Use High-Level Concurrency Abstractions
Speed Up Your Program

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.function.Executable;


public class JunitAssertionsTest {

    public void testException() {
        Executable when = () -> pippo();
        Assertions.assertThrows(IOException.class, when);

    private void pippo() throws IOException {
        throw new IOException("ciao");