jeudi 31 décembre 2020

Value objects

Dans la littérature DDD, les value objects sont de simple classes dont l'égalité est défini par les valeurs des champs, ce qui permet de les identifier dans la mémoire contrairement au entité (par la valeur de l'identifiant), Une bonne pratique est de garder ces classes immuable si on a besoin d'une nouvelle instance on la crée, parmi les avantages aussi l'amélioration des performances et la facilité de création et destruction avec le Garbage collector lorsqu'ils ne sont plus référence .


L'utilisation des entités peut avoir aussi un impact sur les performances de l'application.



https://stackoverflow.com/questions/679005/how-are-value-objects-stored-in-the-database/681106#681106


mardi 29 décembre 2020

Angular : Tips to How To Proxy To Backend Server

 Instead of hard coding http://localhost:8080/api to call the backend.

Here's a tips to how to proxy to backend server only for developement, I don't know if there an alternative for production environement:

First you create a file : proxy.conf.json
when you specify your endpoint,

{ "/api/*": { "target": "http://localhost:8080", "secure": false, "logLevel": "debug", "changeOrigin": true }}

Then you launch you server like ng serve --proxy-config proxy.conf.json
or you can speficy that on your package.json in "start" then npm start.

mercredi 23 décembre 2020

[Maven] Maven - How to remove module-info.class warning for shaded .jar?

 <build> 

    <plugins>        <plugin>          <artifactId>maven-shade-plugin</artifactId>          <version>3.2.1</version>          <executions>            <execution>              <phase>package</phase>              <goals>                <goal>shade</goal>              </goals>            </execution>          </executions>          <configuration>            <finalName>chapter4</finalName>            <!-- Using filtering in order to get rid of nasty warnings generated by shading module-info-->            <filters>              <filter>                <artifact>*:*</artifact>                <excludes>                  <exclude>module-info.class</exclude>                </excludes>              </filter>            </filters>          </configuration>        </plugin>      </plugins>    </build> 

The key line is the <exclude>module-info.class</exclude>. The filter excludes that file whenever it sees it, in any artifact (*:* = any artifact). (The other three excludes I use to get rid of bugs with signature files in dependencies)

dimanche 20 décembre 2020

Jackson with Feign can't deserialized Spring's org.springframework.data.domain.Sort

  return new ObjectMapper()

        .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
        .setPropertyNamingStrategy(SnakeCaseStrategy.SNAKE_CASE)
        .registerModule(new PageJacksonModule())
        .registerModule(new SortJacksonModule());

https://stackoverflow.com/questions/63924863/jackson-with-feign-cant-deserialized-springs-org-springframework-data-domain-s

mardi 1 décembre 2020

Spring Boot Security Firewall org.springframework.security.web.firewall.RequestRejectedException:

 When adding a gateway like zuul in front of legacy application, you may encounter some errors thrown by Spring security like :

org.springframework.security.web.firewall.RequestRejectedException: The request was rejected because the URL contained a potentially malicious String ";"

Check if your server tomcat add jsessionid into the url with ";", to disable it add:<session-config>
    <tracking-mode>COOKIE</tracking-mode>
</session-config>
or in context.xml 
add coockies true to <context>

Since  Spring Boot Security gives us a fully functional HTTP Firewall out of the box, 

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>

HttpFirewall | Black List

We end off with the URL black list which rejects http requests which contain the following …

  • semicolons. You can override this with setAllowSemicolon(boolean)
  • URL encoded forward slash. (represented as %2f)  You can override this with setAllowUrlEncodedSlash(boolean)
  • Backslash. You can override this with setAllowBackSlash(boolean)
  • URL encoded percent sign (represented as %25). You can override this with setAllowUrlEncodedPercent(boolean)
  • URL encoded period (represented as %2e). You can override this with setAllowUrlEncodedPeriod(boolean)
You can customise HttpFirewall like that : 


/*@Bean
public HttpFirewall firewall(){
StrictHttpFirewall firewall = new StrictHttpFirewall();
firewall.setAllowSemicolon(true);
return firewall;
}*/

RFC 8693 - OAuth 2 How to exchange a JWT to new one with STS?

Token exchange is a responsability of the STS.

In order to exchange a token from Domain A to Domain B,

We need to send a POST request with the original JWT in the form data, you need to specify:

grant_type : token_exchange

subject_token : put your Original JWT token

subject_token_type : jwt 

some private key value like audience

From RFC 8693 : 

  • grant_type
REQUIRED. The value "urn:ietf:params:oauth:grant-type:token- exchange" indicates that a token exchange is being performed.
  • subject_token
REQUIRED. A security token that represents the identity of the party on behalf of whom the request is being made. Typically, the subject of this token will be the subject of the security token issued in response to the request.
  • subject_token_type
REQUIRED. An identifier, as described in Section 3, that indicates the type of the security token in the "subject_token" parameter.

more details https://tools.ietf.org/html/rfc8693
Also chapter 7.6 of Microservices Security In Action

lundi 30 novembre 2020

OpenSSL speed test : pour comparer la vitesse des differentes algorithmes des-cbc des-ede3 aes-128-cbc aes-256-cbc

La commande openssl:  openssl speed -elapsed des-cbc des-ede3 aes-128-cbc aes-256-cbc
nous montre combien de données chaque algorithme peut traiter en 3secondes, plus nous avons blocs plus l'algorithme est rapide :
Pour conclure AES-128  est le plus rapide car il traite plus de données que les autres algorithmes  (voir  le resumé en bas de la capture d'ecran):



jeudi 5 novembre 2020

How to set memory limit for your Java containers?


In earlier versions of Java 8 (before update version 192), the JVM has no knowledgeof any limits that the container will enforce: when it inspects the environment to find out how much memory is available so it can calculate its default heap size, it will see all the memory on the machine (instead of,as we would prefer, the amount of memory the Docker container is allowed touse)

The real issue here is the memory: the maximum size of the heap will potentially be larger than the memory assigned to the Docker container.

When the heap grows to that size, the Docker container (and hence the JVM) will be killed.

As java 11 (10+) can automatically detect the container's memory you can set memory limit on your container and it should WAI:
docker run -m 512 .... 

 https://www.upnxtblog.com/index.php/2019/03/14/how-to-set-memory-limit-for-your-java-containers/ 

https://stackoverflow.com/questions/64703776/how-to-set-memory-limit-for-java-11-inside-docker/64705449#64705449

https://blogs.oracle.com/java-platform-group/java-se-support-for-docker-cpu-and-memory-limits

-XX:+UnlockExperimentalVMOptions -XX:+UseCGroupMemoryLimitForHeap : permet de ne limiter la taille de la JVM qu'à ce que peux supporter le conteneur. 

-XX:+UnlockDiagnosticVMOptions -XX:NativeMemoryTracking=summary -XX:+PrintNMTStatistics : log des informations sur l'occupation des espaces mémoires propres à la JVM.


lundi 19 octobre 2020

IntelliJ : Where is my app placed when deploying to Tomcat using IntelliJ IDEA?

CATALINA_HOME vs CATALINA_BASE :

Il ne peut y avoir qu’une seule variable d’environnement CATALINA_HOME

Pour permettre à plusieurs instances de Tomcat de s’exécuter sur la même machine, l’installation des instances du serveur est un peu particulière.

La solution consiste à utiliser la variable d’environnement CATALINA_BASE. Cette variable permet de faire référence au répertoire contenant la configuration spécifique d’une instance. Lorsqu’une seule instance de Tomcat fonctionne, la valeur de cette variable est copiée de CATALINA_HOME.

In IntelliJ IDEA the application does not turn up on Tomcat webapps directory. 

Your artifacts are in directory, for example:

${dir.to.idea.project}\YourWebApp\out\artifacts

This is default directory created by IntelliJ.

Tomcat configuration is in the different folder. I am using windows 7. So it is:

CATALINA_BASE C:\Users\User\.IntelliJIdea10\system\tomcat\YourApplicationName

 https://stackoverflow.com/questions/10461702/where-is-my-app-placed-when-deploying-to-tomcat-using-intellij-idea


Yes, you can direct CATALINA_BASE to be in CATALINA_HOME.

But common practice is to use an external base folder. This keeps your original Tomcat folder pristine, in original condition. Also makes housekeeping a bit easier with multiple projects that might be making use of Tomcat. Each project with its own base folder keeps their own stuff neatly segregated.

Either way, you specify the base folder when configuring IntelliJ to know about Tomcat. Look in Preferences > Build, Execution, Deployment > Application Servers. Click the + icon button to set up a new configuration of Tomcat with IntelliJ, displaying the dialog box shown next. Click the folder icon within the Tomcat base directory field to select your pre-configured base folder.

screenshot of <code>Preferences</code> > <code>Build, Execution, Deployment</code> > <code>Application Servers</code> > <code>Tomcat home directory</code>.

Note in my example screen shot my own practice. I keep Tomcat at the top of my Unix/macOS home folder. I create a folder for my various projects’ base folders named apache-tomcat-base so it abuts the Tomcat folder(s) alphabetically. I then nest a project-specific folder, using Unix-style naming to avoid problems (no SPACE characters, simple, short) — such as example_app seen here. I might further nest version-number named folders if I am working with different versions of Tomcat, such a 9.0.14 (not usual).

CRUCIAL: IntelliJ unfortunately refuses to configure this external base folder. I was spoiled with NetBeans doing this for me automatically. But in IntelliJ, despite having paid money for the Ultimate edition to get the Application Server support feature, I must configure the base folder manually. See my Question on this issue.

  1. Go into the Tomcat folder, copy the conf folder.
  2. Paste into the nested base folder we created.

enter image description here

Lastly, set up a Run/Debug Configuration for your web app. Access the dialog box shown next by using the pop-up menu next to the Run & Debug icons in upper-right corner of IntelliJ. Notice the Application server field, where we select the IntelliJ-Tomcat configuration we established as shown above.

Screenshot of “Run/Debug Configuration > Tomcat Server > Run external Tomcat” dialog box

Bonus Tip: Avoid using the After launch checkbox. Nasty bug causes my web app to double-launch within Tomcat. Just switch to the web browser manually, keep a bookmark for your localhost:8080 URL.

mardi 15 septembre 2020

jeudi 4 juin 2020

Java : how to check the jdk version used to compile a .class file

On Unix/Linux:
javap -verbose MyClass | grep "major"
On Windows:
javap -verbose MyClass | findstr "major"
major version number of the class file format being used
  • Java 14 uses major version 58
  • Java 13 uses major version 57
  • Java 12 uses major version 56
  • Java 11 uses major version 55
  • Java 10 uses major version 54
  • Java 9 uses major version 53
  • Java 8 uses major version 52
  • Java 7 uses major version 51
  • Java 6 uses major version 50
  • Java 5 uses major version 49
  • Java 1.3 uses major version 47
  • Java 1.2 uses major version 46
  • Java 1.4 uses major version 48
https://en.wikipedia.org/wiki/Java_class_file#General_layout
https://stackoverflow.com/questions/1096148/how-to-check-the-jdk-version-used-to-compile-a-class-file

jeudi 21 mai 2020

Quick guide to API Versioning Strategies to avoid breaking changes pros and cons of each strategie non exhaustive

Here's 5 strategies for API versionning, the most popular strategies : URI via Path ParamCustome header via Accept

Coordinating a breaking change is not easy

First identify if it's a Breaking changes:
  • Non-Breaking changes (No effect on existing API)
  • Breaking changes (Not backword compatible, Versioning helps transition) -->  HTTP Status 500 Relaese changes and still support the older one
  • Overhaul (All new API, Beyond versioning)
API Versioning typical lifespan:
v1 - first release
v2 - second release, notify consumers v1 version is deprecated
v3 - remove v1 (optional)

Recap for API lifecycle :



Semantic Versioning 2.0.0 smever.org

API URLs typically use MAJOR versions

API Versioning Strategies :
  • URI  (via Path Param)Version is embededded in URI --> v1, v2 works with caching where is key
    • Cons : 
      • creates whole new tree in each version, require testing and validation.
      • URI itself is changing 
    • Pors  : developer friendly
  • Content Negotiation via Media Type :  like application/json, used server side to determine what version to use for call
    • Define vendor specific media types
    • Example : application/vnd.softwarquality.v1+json 
    • application/vnd.softwarquality.v2+json 
    • Pors : URI does not change.
    • Cons : non standard media type used
  • Header via Custom header (Accept): Define custom header for version information
    • Example : Accpet-version : v1,  and define a value like v1 or v2
    • Server neds to look for the header and value to determine which version to use
    • Pors : URI  does not change, better than overloaded media type
    • Cons : 
  • Request parameter (Query Param): parameter with version information, parsed with to server to determine which version to use
    • Example : /api/products?version=v1
    • Pors : URI does not change.
    • Cons : routing request more difficult 
  • No strategy rewrite
Most popular strategies : URI, Custom header

Conculsion : 
INMO Custom header is the best strategie, since URL resource is unique even if we change API version.
Please add in the comment section other pros and cons.