Why Spring Webflux is better than HttpClient – HowTo in Java

A lot of Boilerplate Code can be avoided.

AND: it is reactive, non-blocking.

Example (really, an example) – the ‚old way‘:

        HttpPost request = new HttpPost("http://www.someurl.de");
        request.setHeader(HttpHeaders.ACCEPT, ContentType.APPLICATION_JSON.getMimeType());
        request.setHeader(HttpHeaders.CONTENT_TYPE, 
                                              ContentType.APPLICATION_JSON.getMimeType());

        String json = someJsonConverter.toJson(someRequestDto);
        HttpEntity stringEntity = new StringEntity(json, ContentType.APPLICATION_JSON);
        request.setEntity(stringEntity);

        try {
            CloseableHttpResponse response2 = httpclient.execute(request);

            if (HttpStatus.SC_CREATED != response2.getStatusLine().getStatusCode()) {
                //TODO eventually handle http statuus additionally
                return returnHandleAndDoNotThrow();
            }
            SomeResponseDto responseDto = (SomeResponseDto) 
                someJsonConverter.toDto(EntityUtils.toString(response.getEntity()), 
                                                               SomerResponseDto.class);
            return Optional.ofNullable(responseDto);
        } catch (IOException e) {
            return Optional.empty();;
        }

The new way:

        Function<UriBuilder, URI> function = uriBuilder ->  
                                                  uriBuilder.path("/somePath").build();
        return client.post()
                .uri(function)
                .accept(MediaType.APPLICATION_JSON)
                .contentType(MediaType.APPLICATION_JSON)
                .body(Mono.just(someDtoInstance), SomeDto.class)
                .exchange()
                .block()
                .bodyToFlux(someResponseDto.class);
//any errors, status codes are handled by a filter which you can define as follows:

Howto:

I am using Spring Boot for this, so I do have a Config class.

import ...
import org.springframework.context.annotation.Bean;
import reactor.core.publisher.Mono;
import org.springframework.web.reactive.function.client.ExchangeFilterFunction;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.context.annotation.Configuration;


@Configuration
public class WebClientConfig {

    //Create the Bean for Autowiring
    @Bean
    public WebClient webClient() {
        return WebClient.builder().filter(someStatusHandlingFilter()).build();
    }
    
    //Handle status codes
    public static ExchangeFilterFunction someStatusHandlingFilter() {
        return ExchangeFilterFunction.ofResponseProcessor(clientResponse -> {
            if ((clientResponse.statusCode().is4xxServerError() 
                || clientResponse.statusCode().is5xxClientError())) {
                return clientResponse                        
                        .bodyToMono(SomeException.class)
                        .flatMap(errorBody -> {
                            return Mono.error(someExceptionToLog);
                        });
            } else {
                return Mono.just(clientResponse);
            }
        });
    }
}

Maven:

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-integration</artifactId>
            <version>your latest version goes here</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-webflux</artifactId>
            <version>your latest version goes here</version>
        </dependency>

Howto generate a new SSH key pair

ssh-keygen -t ed25519 -C "email@example.com"

Note that in this example we use an ed25519 key.

The -c is providing a comment to divide the key amongst others.

I alwas use the suggested path and just klick enter 😉

How to create an NPM Package

You want reusable components, elements? Flexible structure?
Separation of concerns, decoupling in your JS Code?

A good strategy is to create an NPM Package.

  • Identify the code you would like to decouple.
  • create a new project
  • create an src folder
  • paste the JS or TS files in that folder
  • install the missing dependencies like Typescript, TSlint, Material UI
  • Write UNIT Tests to test your code before publishing it

I use JEST and to include the relevant Code, add this to your tsconfig.json:

    "include": ["src/**/*"],
    "exclude": ["node_modules", "**/__tests__/*"] 

Before the package is published, you can test it locally:

  • In your terminal, run npm link
  • This will compile and create a symbolic link, pointing to another directory/files on your development machine.
  • Now include the new package as a dependency. In your terminal, run npm link <module_name>
  • If everything can be imported and used, the test work and you are satisfied, perform npm unlink --nosave <module_name> on your main projects directory. This will remove the symbolic link.
  • Then run npm unlink to also remove the global link.

Now you have extracted and published Code as NPM package.

JUnit Test String contained / contains String

With the Hamcrest Matchers, do this:

//imports
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.StringContains.containsString;

//assert
assertThat(actualData, containsString(expectedData));

React – use CSS depending on states (change class according to a variable’s state)

For this example I use React Hooks and a Component with a stateful variable.
When the variable is changed, the CSS class is changed accordingly.
The part in the component is automatically re-rendered on the fly.

//The variable is called 'active'. 
//This is an example. Choose any name.
const [active, setActive] = useState(0);

We use the constant #getStyle to return a CSS class name based on the variable.

    const getStyle = (input) => {
        if (input === active){
            // This example is freely chosen. 
            //button-active is the CSS class' name
            return "button-active";
        } else {
            return "button-inactive";
        }
    };

The return statement returns rendered HTML.

//The hard coded value 0 can be any dynamic 
//variable from JS or React, like one from the 
//props (Properties) object
return (
  <div className={getStyle(0)}>
  </div>
);
  • Stateful variable called ‚active‘
  • Const named #getStyle with an input parameter
  • render method returning HTML with a css class name
  • Input is provided to the #getStyle const
  • If the variable ‚active‘ is changed by the application somewhere, the HTML is re-rendered
  • The input is compared to the variable and the name of the CSS class returned